-
Notifications
You must be signed in to change notification settings - Fork 0
/
0207. Course Schedule
44 lines (36 loc) · 1.13 KB
/
0207. Course Schedule
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
https://leetcode.com/problems/course-schedule/description/
Time: O(m+n)
Space: O(m+n)
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
int visited = 0;
int[] indegree = new int[numCourses];
Map<Integer, Set<Integer>> adj = new HashMap<>();
for (int i = 0; i < numCourses; i++) {
adj.put(i, new HashSet<>());
}
for (int[] prerequisite : prerequisites) {
int dest = prerequisite[0];
int src = prerequisite[1];
adj.get(src).add(dest);
indegree[dest]++;
}
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < numCourses; i++) {
if (indegree[i] == 0) {
stack.push(i);
}
}
while (!stack.isEmpty()) {
int node = stack.pop();
visited++;
for (int neighbor : adj.get(node)) {
indegree[neighbor]--;
if (indegree[neighbor] == 0) {
stack.push(neighbor);
}
}
}
return visited == numCourses;
}
}