-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathCycleDetection.java
46 lines (37 loc) · 1.14 KB
/
CycleDetection.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
public class CycleDetection {
private Graph G;
private boolean[] visited;
private boolean hasCycle = false;
public CycleDetection(Graph G){
this.G = G;
visited = new boolean[G.V()];
for(int v = 0; v < G.V(); v ++)
if(!visited[v])
if(dfs(v, v)){
hasCycle = true;
break;
}
}
// 从顶点 v 开始,判断图中是否有环
private boolean dfs(int v, int parent){
visited[v] = true;
for(int w: G.adj(v))
if(!visited[w]){
if(dfs(w, v)) return true;
}
else if(w != parent)
return true;
return false;
}
public boolean hasCycle(){
return hasCycle;
}
public static void main(String[] args){
Graph g = new Graph("g.txt");
CycleDetection cycleDetection = new CycleDetection(g);
System.out.println(cycleDetection.hasCycle());
Graph g2 = new Graph("g2.txt");
CycleDetection cycleDetection2 = new CycleDetection(g2);
System.out.println(cycleDetection2.hasCycle());
}
}