-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourseScheduleOne.java
More file actions
42 lines (34 loc) · 986 Bytes
/
Copy pathCourseScheduleOne.java
File metadata and controls
42 lines (34 loc) · 986 Bytes
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
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
HashMap<Integer, List<Integer>> graph = new HashMap<>();
for (int n = 0; n < numCourses; n++) {
graph.put(n, new ArrayList<Integer>());
}
for (int i = 0; i < prerequisites.length; i++) {
graph.get(prerequisites[i][1]).add(prerequisites[i][0]);
}
int[] visited = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
if (visited[i] == 0 && !dfs(i, graph, visited)) {
return false;
}
}
return true;
}
private boolean dfs(int node, HashMap<Integer, List<Integer>> graph, int[] visited) {
if (visited[node] == 1) {
return true;
}
if (visited[node] == -1) {
return false;
}
visited[node] = -1;
for (int i = 0; i < graph.get(node).size(); i++) {
if (!dfs(graph.get(node).get(i), graph, visited)) {
return false;
}
}
visited[node] = 1;
return true;
}
}