[JS]求解哈米尔顿回路及路径
来源:9-3 实现哈密尔顿回路的算法
Potter520
2023-02-24
利用老师教的知识,自己先手动实现一遍
/**
* graph
* 0 - 3
* | \ |
* 1 - 2
*
*
* 0 - 3
* \ |
* 1 - 2
* @param {*} graph
*/
function hamiltonCycle(graph, s) {
let path = [];
let size = graph.length;
let visited = Array(size).fill(false);
let flag = false;
let count = 0;
let clonePath = null;
function print() {
console.log("-".repeat(count), ...arguments);
}
function dfs(v, parent) {
visited[v] = true;
path.push(v);
++count;
print("push:", v);
print("push: path=", path);
print("visited:", visited);
for (const w of graph[v]) {
if (flag) {
break;
}
if (!visited[w] && !flag) {
dfs(w, v);
} else if (visited[w] && w != parent) {
if (count === size) {
flag = true;
t = w;
clonePath = path.slice(0);
print("find solution: ", path);
}
}
}
visited[v] = false;
print("pop:", path[path.length - 1]);
path.pop();
print("pop: path=", path);
print("visited:", visited);
--count;
print("pop: path=", path);
}
dfs(s, s);
if (!flag) {
console.log("找不到哈米尔顿回路");
return [];
}
clonePath.push(s);
return clonePath.reverse();
}
let path = hamiltonCycle(
[
[3, 2, 1],
[0, 2],
[1, 0, 3],
[0, 2],
],
0,
0
);
console.log(path.join("->"));
输出结果
- push: 0
- push: path= [ 0 ]
- visited: [ true, false, false, false ]
-- push: 3
-- push: path= [ 0, 3 ]
-- visited: [ true, false, false, true ]
--- push: 2
--- push: path= [ 0, 3, 2 ]
--- visited: [ true, false, true, true ]
---- push: 1
---- push: path= [ 0, 3, 2, 1 ]
---- visited: [ true, true, true, true ]
---- find solution: [ 0, 3, 2, 1 ]
---- pop: 1
---- pop: path= [ 0, 3, 2 ]
---- visited: [ true, false, true, true ]
--- pop: path= [ 0, 3, 2 ]
--- pop: 2
--- pop: path= [ 0, 3 ]
--- visited: [ true, false, false, true ]
-- pop: path= [ 0, 3 ]
-- pop: 3
-- pop: path= [ 0 ]
-- visited: [ true, false, false, false ]
- pop: path= [ 0 ]
- pop: 0
- pop: path= []
- visited: [ false, false, false, false ]
pop: path= []
0->1->2->3->0
写回答
1回答
-
liuyubobobo
2023-02-25
感谢分享。继续加油!:)
00
相似问题