-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution207.java
More file actions
executable file
·33 lines (33 loc) · 1.01 KB
/
Copy pathSolution207.java
File metadata and controls
executable file
·33 lines (33 loc) · 1.01 KB
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
class Solution207 {
public boolean canFinish(int numCourses, int[][] prerequisites) {
// 邻接表表示图
int[] inValues = new int[numCourses];
List<List<Integer>> adjacencyList = new ArrayList<>();
for (int i = 0; i < numCourses; i++) {
adjacencyList.add(new ArrayList<>());
}
for (int[] p : prerequisites) {
adjacencyList.get(p[0]).add(p[1]);
inValues[p[1]]++;
}
// 拓扑排序
Queue<Integer> queue = new ArrayDeque<>();
int flag = 0;
for (int i = 0; i < numCourses; i++) {
if (inValues[i] == 0) {
queue.offer(i);
flag++;
}
}
while (!queue.isEmpty()) {
int t = queue.poll();
for (int adj : adjacencyList.get(t)) {
if (--inValues[adj] == 0) {
flag++;
queue.offer(adj);
}
}
}
return flag == numCourses;
}
}