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 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)