-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSolution207.java
69 lines (53 loc) · 1.64 KB
/
Solution207.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
66
67
68
69
package leetcode.graph;
import java.util.LinkedList;
public class Solution207 {
public static void main(String[] args) {
System.out.println(new Solution207().canFinish(2, new int[][]{new int[]{0, 1}}));
}
public boolean canFinish(int numCourses, int[][] prerequisites) {
Digraph digraph = new Digraph(numCourses, prerequisites);
return !digraph.isHasCycle();
}
static class Digraph {
int V;
private LinkedList<Integer>[] adj;
private boolean[] marked;
private boolean[] onStack;
private boolean hasCycle;
public Digraph(int v, int[][] prerequisites) {
hasCycle = false;
this.V = v;
marked = new boolean[V];
onStack = new boolean[V];
adj = new LinkedList[V];
for (int i = 0; i < adj.length; i++) {
adj[i] = new LinkedList<>();
}
for (int[] prerequisite : prerequisites) {
adj[prerequisite[1]].add(prerequisite[0]);
}
for (int i = 0; i < V; i++) {
dfs(i);
}
}
private void dfs(int v) {
if (hasCycle) {
return;
}
marked[v] = true;
onStack[v] = true;
for (Integer w : adj[v]) {
if (!marked[w]) {
dfs(w);
} else if (onStack[w]) {
hasCycle = true;
return;
}
}
onStack[v] = false;
}
public boolean isHasCycle() {
return hasCycle;
}
}
}