题目链接:207. 课程表 - 力扣(LeetCode)
先修课程,判断课程能不能修完,这是一个判断拓扑有序的问题,看看会不会成环
先建立有向图,记录每个顶点的入度,把入度为0的入队列
入度为0的说明没有先修课程,取出来修,并将相连的节点的入度减一,说明先修课程已经修了一个了,再判断有没有新的课程可以修的入队
最后判断修了的课程和要修的课程数目是否相等
代码语言:javascript复制class Solution {
public:
bool canFinish(int numCourses, vector<vector<int> > &prerequisites) {
vector<vector<int> > map(numCourses, vector<int>(numCourses));
vector<int> inDegree(numCourses);
for (auto must: prerequisites) {
int from = must[1], to = must[0];
inDegree[to];
map[from][to] = 1;
}
queue<int> learned;
for (int i = 0; i < numCourses; i)
if (inDegree[i] == 0)
learned.emplace(i);
int pass = 0;
while (!learned.empty()) {
int passed = learned.front();
learned.pop();
pass ;
for (int i = 0; i < numCourses; i) {
if (map[passed][i]) {
--inDegree[i];
if (inDegree[i] == 0)
learned.emplace(i);
}
}
}
if (pass == numCourses)
return true;
return false;
}
};