-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCycleDetection.java
More file actions
56 lines (43 loc) · 1.5 KB
/
Copy pathCycleDetection.java
File metadata and controls
56 lines (43 loc) · 1.5 KB
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
import java.util.ArrayList;
public class CycleDetection {
private Graph G;
private boolean[] visited;
private boolean hasCycle = false;
public CycleDetection(Graph G){
if(G.isDirected())
throw new IllegalArgumentException("只支持无向图");
this.G = G;
visited = new boolean[G.V()];
// 多包一层for,防止有多个联通分量
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) // 判断是否有环:一个相邻节点w被访问过并且 该相邻节点w不是当前节点v的上个节点,则说明有环
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("g8.txt",true);
CycleDetection cycleDetection2 = new CycleDetection(g2);
System.out.println(cycleDetection2.hasCycle());
}
}