Middle-题目86：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.

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) 从网中删除此顶点及所有出边。

• 本文已收录于以下专栏：

Leetcode 207 Course Schedule 课程表

• smile_watermelon
• 2015年08月10日 18:05
• 2815

leetcode 207: Course Schedule

leetcode 207 : Course Schedule
• xudli
• 2015年05月20日 05:07
• 4324

[leetcode-207]Course Schedule（java）

• zdavb
• 2015年08月26日 15:23
• 461

【LeetCode】207. Course Schedule

• u011613729
• 2016年05月30日 23:40
• 675

LeetCode 207 - Course Schedule

• lisong694767315
• 2015年05月07日 02:24
• 2763

【LeetCode】Course Schedule 解题报告

【题目】 There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses may ...
• ljiabin
• 2015年05月19日 17:05
• 15039

[leetcode] 207. Course Schedule 解题报告

• qq508618087
• 2016年02月26日 14:10
• 827

LeetCode算法题目：Course Schedule

• qq_24835809
• 2017年06月24日 18:19
• 101

207. Course Schedule

class Solution { public: bool canFinish(int numCourses, vector>& prerequisites) { map co...
• sinat_31360161
• 2016年02月23日 21:43
• 253

207. Course Schedule - Medium

Description There are a total of n courses you have to take, labeled from 0 to n - 1. Some courses...
• qq_33559972
• 2018年01月11日 13:53
• 12

举报原因： 您举报文章：Middle-题目86：207. Course Schedule 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)