lc 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?
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.
DFS Accepted##
这是一个非常典型的拓扑排序问题,整个问题可以总结为如何判断有向图是否有环。通过对图上的每一个点做DFS,如果都是无环的,则能证明课程安排是合理的。注意,点的状态有三种,分别是没被访问,第一次访问后以及第二次访问后。
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<set<int>> graph(numCourses);
bool cycle = false;
for (auto prev : prerequisites) {
graph[prev.second].insert(prev.first);
}
vector<int> visited(numCourses, 0);
for (int i = 0; i < numCourses; i++) {
if (cycle) return false;
if (visited[i] == 0) dfs(i, graph, visited, cycle);
}
return !cycle;
}
void dfs(int nodei, vector<set<int>> &graph, vector<int> &visited, bool &cycle) {
if (visited[nodei] == 1) {
cycle = true;
return;
}
visited[nodei] = true;
for (auto i : graph[nodei]) {
dfs(i, graph, visited, cycle);
if (cycle) return;
}
visited[nodei] = 2;
}
};