-
Notifications
You must be signed in to change notification settings - Fork 2
/
HamiltonPath.java
65 lines (55 loc) · 1.29 KB
/
HamiltonPath.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.github.datastructureandalgorithm.graph.chapter9;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HamiltonPath {
private Graph G;
private int s;
private boolean[] visited;
private int[] pre;
private int end;
private int left;
public HamiltonPath(Graph G, int s) {
this.G = G;
this.s = s;
visited = new boolean[G.V()];
pre = new int[G.V()];
end = -1;
this.left = G.V();
dfs(s, s);
}
private boolean dfs(int v, int parent) {
visited[v] = true;
pre[v] = parent;
left--;
if (left == 0) {
end = v;
return true;
}
for (int w : G.adj(v)) {
if (!visited[w]) {
if (dfs(w, v)) return true;
}
}
visited[v] = false;
left++;
return false;
}
/**
* 返回哈密尔顿路径
*
* @return
*/
public List<Integer> result() {
List<Integer> res = new ArrayList<>();
if (end == -1) return res;
int cur = end;
while (cur != s) {
res.add(cur);
cur = pre[cur];
}
res.add(s);
Collections.reverse(res);
return res;
}
}