版权声明:本文由博主@杨领well发表在http://blog.csdn.net/yanglingwell,如果转载请注明出处。 https://blog.csdn.net/yanglingwell/article/details/82780767
LeetCode: 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?
Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: 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.
- You may assume that there are no duplicate edges in the input prerequisites.
解题思路 —— 拓扑排序
遍历所有节点找出没有入度的节点,然后删掉。重复操作,直到无法操作。如果最后有剩余的节点,则返回 false
, 否则返回 true
。
AC 代码
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
unordered_set<int> travelVertices;
multimap<int, int> adjVer; // 邻接矩阵
bool hasNewVer = true;
for(auto iter = prerequisites.begin(); iter != prerequisites.end(); ++iter)
{
adjVer.insert({iter->second, iter->first});
}
while(travelVertices.size() != numCourses && hasNewVer)
{
// 记录每个课程的入度
vector<int> courses(numCourses, 0);
for(size_t i = 0; i < numCourses; ++i)
{
for(auto iter = adjVer.find(i); iter != adjVer.end() && iter->first == i; ++iter)
{
if(travelVertices.find(iter->second) == travelVertices.end())
{
++courses[iter->first];
}
}
}
hasNewVer = false;
for(size_t i = 0; i < courses.size(); ++i)
{
// 入度是 0 的课程可以上
if(courses[i] == 0 && travelVertices.find(i) == travelVertices.end())
{
travelVertices.insert(i);
hasNewVer = true;
}
}
}
return (travelVertices.size() == numCourses);
}
};