拓扑排序：课程表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.

class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {

vector<int> inDgree(numCourses,0);

int len = prerequisites.size();
for (int i = 0; i < len; i++){
pair<int, int> p = prerequisites[i];

inDgree[p.first]++;
}
}

queue<int> Q;

for (int i=0; i < numCourses; i++){
if (inDgree[i] == 0)
Q.push(i);
}

while (!Q.empty()){
int front = Q.front();
Q.pop();

inDgree[i]--;
if (inDgree[i] == 0){
Q.push(i);
}
}

}

for (int i: inDgree){
if (i)
return false;
}
return true;
}

};


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

拓扑排序：课程表Course Schedule2

https://leetcode.com/problems/course-schedule-ii/class Solution { public: vector findOrder(int n...
• gao1440156051
• 2016年05月31日 16:44
• 413

拓扑排序：课程表Course Schedule

There are a total of n courses you have to take, labeled from 0 to n - 1.Some courses may have prere...
• gao1440156051
• 2016年05月31日 16:28
• 704

拓扑排序 ---排课表----数据结构

• 2010年06月13日 07:34
• 414KB
• 下载

Leetcode 207 Course Schedule 课程表

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

Leetcode 210 Course Schedule II 课程表II

• smile_watermelon
• 2015年08月14日 16:29
• 747

数据结构课设拓扑排序源代码（教学计划安排）

• 2014年09月07日 19:07
• 375KB
• 下载

排课程序（拓扑排序）

• 2012年01月08日 00:04
• 188KB
• 下载

【LeetCode】Course Schedule II 解题报告

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

【LeetCode】207. Course Schedule

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

lintcode(616)安排课程

Description: 你需要去上n门九章的课才能获得offer，这些课被标号为 0 到 n-1 。 有一些课程需要“前置课程”，比如如果你要上课程0，你需要先学课程1，我们用一个匹配来...
• sunday0904
• 2017年05月18日 09:59
• 836

举报原因： 您举报文章：拓扑排序：课程表Course Schedule 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)