leetcode 207 Course Schedule
z

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

1
2
3
4
Input: 2, [[1,0]] 
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.

Example 2:

1
2
3
4
5
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.

Note:

  1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
  2. You may assume that there are no duplicate edges in the input prerequisites.

  • 等价于判断图中是否存在环
  • 对于图的表述,可以使用邻接矩阵入度来表示
  • 对所有入度为0的课程,学习他。
  • 学习完一个课程之后,将以该课程为prerequisite的课程的入度都减一
  • 如果存在一个课程入度为0,将其加入待学习的set中
  • 每学习一个课程,count一下它
  • 最后比较count的数目是否为所有课程的数目
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
class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
if (prerequisites.length == 0 || prerequisites[0].length == 0) return true;
LinkedList<Integer>[] neighbors = new LinkedList[numCourses];
for (int i=0; i<numCourses; i++) neighbors[i] = new LinkedList<Integer>();
int[] indegree = new int[numCourses];
int n = 0;
for (int[] crs: prerequisites) {
int take = crs[0];
int pre = crs[1];
if (neighbors[pre] == null) {
neighbors[pre] = new LinkedList<Integer>();
}
neighbors[pre].add(take);
indegree[take]++;
}

Queue<Integer> q = new LinkedList<>();

for (int i=0; i<numCourses; i++) {
if (indegree[i] == 0) {
q.offer(i);
}
}

while (!q.isEmpty()) {
int crs = q.poll();
n ++;
for (int pre: neighbors[crs]) {
indegree[pre] --;
if (indegree[pre] == 0) {
q.offer(pre);
}
}
}
return n == numCourses;
}
}