-
Notifications
You must be signed in to change notification settings - Fork 104
/
DirectedCycleDetection.java
49 lines (40 loc) · 1.27 KB
/
DirectedCycleDetection.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
public class DirectedCycleDetection {
private Graph G;
private boolean[] visited;
private boolean[] onPath;
private boolean hasCycle = false;
public DirectedCycleDetection(Graph G){
if(!G.isDirected())
throw new IllegalArgumentException("DirectedCycleDetection only works in directed graph.");
this.G = G;
visited = new boolean[G.V()];
onPath = 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;
onPath[v] = true;
for(int w: G.adj(v))
if(!visited[w]){
if(dfs(w, v)) return true;
}
else if(onPath[w])
return true;
onPath[v] = false;
return false;
}
public boolean hasCycle(){
return hasCycle;
}
public static void main(String[] args){
Graph g = new Graph("ug.txt", true);
DirectedCycleDetection cycleDetection = new DirectedCycleDetection(g);
System.out.println(cycleDetection.hasCycle());
}
}