-
Notifications
You must be signed in to change notification settings - Fork 0
/
L207.java
61 lines (58 loc) · 1.86 KB
/
L207.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
import java.util.ArrayList;
import java.util.List;
class Solution207 {
class Solution {
int[] visited; // 0 unvisited 1 visiting 2 visited
/**
* 207. Course Schedule https://leetcode.com/problems/course-schedule/description/
*
* @param numCourses
* @param prerequisites
* @return
* @timeComplexity O(V + E)
* @spaceComplexity O(V)
*/
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites.length == 0) {
return true;
}
visited = new int[numCourses];
List<List<Integer>> graph = new ArrayList<>();
// Initialize graph
for (int i = 0; i < numCourses; i++) {
graph.add(new ArrayList<>());
}
// Populate graph
for (int i = 0; i < prerequisites.length; i++) {
graph.get(prerequisites[i][0]).add(prerequisites[i][1]);
}
for (int i = 0; i < numCourses; i++) {
if (visited[i] == 2) {
continue;
}
if (hasCycle(graph, i)) {
return false;
}
}
return true;
}
public boolean hasCycle(List<List<Integer>> graph, int src) {
List<Integer> destinations = graph.get(src);
for (int dest : destinations) {
if (visited[dest] == 2) {
continue;
}
// Its a cycle!
if (visited[dest] == 1) {
return true;
}
visited[dest] = 1;
if (hasCycle(graph, dest)) {
return true;
}
visited[dest] = 2;
}
return false;
}
}
}