算法题目 : Course Schedule
算法题目描述:
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 abouthow a graph is represented
- You may assume that there are no duplicate edges in the input prerequisites.
算法分析:
这就是典型的拓扑排序的问题了,问我们是否可以依次输出这些课并且不形成环。我们就可以用拓扑排序依次输出度为0的值,并用一个队列存入度为0的节点,然后依次出对,如果最后存在度不为0的节点,就说明存在环。应该就是这样。
算法代码(C++):
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>(0));
vector<int> inDegree(numCourses, 0);
for (auto u : prerequisites) {
graph[u[1]].push_back(u[0]);
++inDegree[u[0]];
}
queue<int> que;
for (int i = 0; i < numCourses; ++i) {
if (inDegree[i] == 0) que.push(i);
}
while (!que.empty()) {
int u = que.front();
que.pop();
for (auto v : graph[u]) {
--inDegree[v];
if (inDegree[v] == 0) que.push(v);
}
}
for (int i = 0; i < numCourses; ++i) {
if (inDegree[i] != 0) return false;
}
return true;
}
};
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int>> graph(numCourses, vector<int>(0));
vector<int> inDegree(numCourses, 0);
for (auto u : prerequisites) {
graph[u[1]].push_back(u[0]);
++inDegree[u[0]];
}
queue<int> que;
for (int i = 0; i < numCourses; ++i) {
if (inDegree[i] == 0) que.push(i);
}
while (!que.empty()) {
int u = que.front();
que.pop();
for (auto v : graph[u]) {
--inDegree[v];
if (inDegree[v] == 0) que.push(v);
}
}
for (int i = 0; i < numCourses; ++i) {
if (inDegree[i] != 0) return false;
}
return true;
}
};