-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathCourse Schedule - Leetcode 207.java
41 lines (33 loc) · 1.15 KB
/
Course Schedule - Leetcode 207.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
import java.util.*;
public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int[] pair : prerequisites) {
graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);
}
final int UNVISITED = 0;
final int VISITING = 1;
final int VISITED = 2;
int[] states = new int[numCourses];
for (int i = 0; i < numCourses; i++) {
if (!dfs(i, graph, states)) {
return false;
}
}
return true;
}
private boolean dfs(int node, Map<Integer, List<Integer>> graph, int[] states) {
if (states[node] == 1) return false; // Cycle detected
if (states[node] == 2) return true; // Already visited
states[node] = 1; // Mark as visiting
if (graph.containsKey(node)) {
for (int neighbor : graph.get(node)) {
if (!dfs(neighbor, graph, states)) {
return false;
}
}
}
states[node] = 2; // Mark as visited
return true;
}
}