Skip to content

Commit 137d335

Browse files
committed
hamilton
1 parent 77e9b91 commit 137d335

File tree

5 files changed

+96
-21
lines changed

5 files changed

+96
-21
lines changed

.idea/workspace.xml

Lines changed: 20 additions & 21 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

g4.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
4 5
2+
0 1
3+
0 2
4+
0 3
5+
1 2
6+
1 3
0 Bytes
Binary file not shown.
2.15 KB
Binary file not shown.

src/HamiltonLoop.java

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import java.util.ArrayList;
2+
import java.util.Collections;
3+
4+
public class HamiltonLoop {
5+
private Graph G;
6+
private boolean[] visited;
7+
private int[] pre;
8+
private int end;
9+
10+
public HamiltonLoop(Graph G){
11+
this.G = G;
12+
visited = new boolean[G.V()];
13+
pre = new int[G.V()];
14+
end = -1;
15+
16+
dfs(0,0);
17+
}
18+
19+
// 深度优先遍历
20+
private boolean dfs(int v,int parent){
21+
visited[v] = true;
22+
pre[v] = parent;
23+
24+
// 遍历相邻节点
25+
for(int w : G.adj(v)){
26+
if(!visited[w]){
27+
if(dfs(w,v)) return true;
28+
}
29+
else if(w == 0 && allVisited()){ // 如果回到起始点0并且所有的点都被访问过了,则找到了哈密尔回路
30+
end = v;
31+
return true;
32+
}
33+
34+
}
35+
36+
// 回溯
37+
visited[v] = false;
38+
return false;
39+
40+
41+
}
42+
43+
private boolean allVisited(){
44+
for(int v = 0;v<G.V();v++){
45+
if(!visited[v]) return false;
46+
}
47+
return true;
48+
}
49+
50+
private ArrayList<Integer> result(){
51+
ArrayList<Integer> res = new ArrayList<>();
52+
if(end == -1) return res;
53+
54+
int cur = end;
55+
while(cur != 0){
56+
res.add(cur);
57+
cur = pre[cur]; // 上一个节点
58+
}
59+
res.add(0);
60+
Collections.reverse(res); // 反
61+
return res;
62+
}
63+
64+
public static void main(String[] args){
65+
66+
Graph g = new Graph("g4.txt");
67+
HamiltonLoop hamiltonLoop = new HamiltonLoop(g);
68+
System.out.println(hamiltonLoop.result());
69+
}
70+
}

0 commit comments

Comments
 (0)