# 【LeetCode】207. Course Schedule

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

Subscribe to see which companies asked this question

### 代码

bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<int>> pre(numCourses);
int N = prerequisites.size();
vector<int> inDegree(numCourses,0);
for (int i=0;i<N;++i){
auto p = prerequisites[i];
inDegree[p.first]++;
pre[p.second].push_back(p.first);
}

queue<int> que;
for (int i=0;i<numCourses;++i){
if (inDegree[i]==0) que.push(i);
}

int count=0;
while(!que.empty()){
int acc=que.front();
que.pop();
++count;
for (auto st:pre[acc]){
if (inDegree[st]==1){
que.push(st);
}
inDegree[st]--;
}
}
return count==numCourses;
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：398341次
• 积分：5027
• 等级：
• 排名：第5811名
• 原创：162篇
• 转载：18篇
• 译文：0篇
• 评论：72条
博客专栏
 LeetCode的Python题解 文章：12篇 阅读：32848
 Android平台的口语对话系统 文章：6篇 阅读：19392
文章分类
阅读排行
最新评论