# 拓扑排序：课程表Course Schedule

556人阅读 评论(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.

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;
}

};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：389701次
• 积分：7975
• 等级：
• 排名：第2668名
• 原创：390篇
• 转载：276篇
• 译文：0篇
• 评论：27条
联系方式
E-mail：gwh_mail@qq.com QQ：1440156051
评论排行
最新评论