###### LeetCode 207 Course Schedule

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?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

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:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

	public static boolean canFinish(int numCourses, int[][] prerequisites) {
int[] id = new int[numCourses];
for (int i = 0; i < numCourses; i++) id[i] = i;
for (int[] pair : prerequisites) {
id[pair[0]] = pair[1];
if (root(id, pair[0]) ) return false;
}
return true;
}

private static boolean root(int[] id, int i) {
int count = 0;
//如果存在i==id[i],证明以i课程最终的前置课程没有前置,就不会有环
while (i != id[i]) {
i = id[i];
count++;
if (count == id.length) return false;//存在环,所以会一直循环,导致count=len
}
return true;
}


	public boolean canFinish2(int numCourses, int[][] prerequisites) {
int[] map = new int[numCourses];

for (int i = 0; i < prerequisites.length; i++)
map[prerequisites[i][1]]++;//记录作为前置课程的course有几个后继,就是点的入度

for (int i = 0; i < map.length; i++)

int count = que.size();
while (!que.isEmpty()) {
int k = que.remove();
for (int i = 0; i < prerequisites.length; i++) {
if (k == prerequisites[i][0]) {
int l = prerequisites[i][1];//k的出度所指向的点,即k需要的先修课程
map[l]--;//去掉一个入度,等于去掉了一条边
if (map[l] == 0) {//入度为0的时候,入队,下个循环时寻找此点的先驱
++count;//得到一个入度为0的点,count加1
}
}
}
}
return count == numCourses;//所有点的入度最后都为0时,无环
}


#### 【LeetCode】207. Course Schedule

2016-05-30 23:40:09

#### leetcode 207: Course Schedule

2015-05-20 05:07:51

#### Leetcode 207 Course Schedule 课程表

2015-08-10 18:05:39

#### [LeetCode]207. Course Schedule 课程表

2018-03-03 21:52:47

#### LeetCode 207 - Course Schedule

2015-05-07 02:24:40

#### [leetcode-207]Course Schedule（java）

2015-08-26 15:23:03

#### LeetCode 207. Course Schedule（课程安排）

2016-05-04 10:03:07

#### leetcode_c++:图：Course Schedule(207)

2016-08-28 15:08:20

#### leetcode_c++:图：Course Schedule II (207)

2016-08-28 15:11:38

#### [leetcode] 207.Course Schedule

2015-07-20 10:45:28

## 不良信息举报

LeetCode 207 Course Schedule