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.
DFS的思想是从一个结点出发,然后访问它的邻接结点,直到访问到已经访问过的结点,这样就证明存在环,return false。
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.
You may assume that there are no duplicate edges in the input prerequisites.
BFS和DFS两种做法。
BFS主要是基于拓扑排序,具体可以看这里。
http://blog.csdn.net/changyuanchn/article/details/17067349
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<unordered_set<int>> graph=make_map(numCourses, prerequisites);
vector<int> degrees=compute_degrees(graph);
for(int i=0; i<numCourses; i++){
int j=0;
for(; j<numCourses; j++) if(!degrees[j]) break;
if(j==numCourses) return false;
degrees[j]=-1;
for(int neigh:graph[j]) degrees[neigh]--;
}
return true;
}
vector<unordered_set<int>> make_map(int numCourses, vector<pair<int, int>>& prerequisites){
vector<unordered_set<int>> graph(numCourses);
for(auto pre : prerequisites)
graph[pre.second].insert(pre.first);
return graph;
}
vector<int> compute_degrees(vector<unordered_set<int>>& graph){
vector<int> degrees(graph.size(), 0);
for( auto neighbor : graph)
for(auto nei:neighbor)
degrees[nei]++;
return degrees;
}
};
DFS的思想是从一个结点出发,然后访问它的邻接结点,直到访问到已经访问过的结点,这样就证明存在环,return false。
需要维护两个数组,一个记录访问过的所有节点,另一个记录本轮循环中的所有节点。
具体可以看discuss。。。https://discuss.leetcode.com/topic/17273/18-22-lines-c-bfs-dfs-solutions/2