# Middle-题目86：207. Course Schedule

67人阅读 评论(0)

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.

public class Solution {
public  boolean canFinish(int numCourses, int[][] prerequisites) {
Map<Integer, Set<Integer>> adjList = new HashMap<Integer,Set<Integer>>();
int[] indegree = new int[numCourses];
for(int i = 0; i<numCourses;i++)
for(int[] edge : prerequisites) {
indegree[edge[1]]++;
}
}
int topoVertical = findZeroIndegree(indegree);
while(topoVertical!=-1) {
indegree[topoVertical] = -1; // -1 stands for visited
indegree[vertical]--;
}
topoVertical = findZeroIndegree(indegree);
}
return isAllVisited(indegree);
}
private int findZeroIndegree(int[] indegree) {
for(int i = 0;i<indegree.length;i++)
if(indegree[i]==0)
return i;
return -1;
}
private boolean isAllVisited(int[] indegree) {
for(int i : indegree)
if(i!=-1)
return false;
return true;
}
}

24ms,beats 47.84%，众数12ms,6.33%
Cmershen的碎碎念：

(1) 选择一个入度为0的顶点并输出之；
(2) 从网中删除此顶点及所有出边。

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：64455次
• 积分：3285
• 等级：
• 排名：第10717名
• 原创：270篇
• 转载：53篇
• 译文：0篇
• 评论：8条
文章分类
阅读排行
最新评论