请点击:原题目链接以打开leetcode题目
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.
思路: 当课程之间构成的graph存在环路时–》“to finish all courses is impossible.”借鉴拓扑排序中的思想,检测graph是否存在环路。
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<vector<bool> > adj(numCourses,vector<bool>(numCourses));//adjadency matrix
for(int i=0;i<prerequisites.size();i++)
adj[prerequisites[i].second][prerequisites[i].first]=1;
if(kahann(adj)) return 1;
else return 0;
}
bool kahann(vector<vector<bool> >& adj){
// 给定邻接矩阵,构造拓扑序列
int N=adj.size();
vector<int> indeg(N,0);
vector<int> S;
vector<int> L;//from S
int sum;
for(int i=0;i<N;i++){
sum=0;
for(int j=0;j<N;j++)
sum+=adj[j][i];
indeg[i]=sum;
if(sum==0) S.push_back(i);
}
int node;
while(!S.empty()){
node=S[0];
L.push_back(node);
S.erase(S.begin());
for(int i=0;i<N;i++){
if(adj[node][i]==0) continue;
adj[node][i]=0;
indeg[i]--;
if(indeg[i]==0 && i!=node) S.push_back(i);
}
}
sum=0;
for(int i=0;i<N;i++){
sum+=indeg[i];
}
if(sum) return false;//有环路
return true; //DAG 无环图
}
};
int main(){
vector<pair<int, int>> prerequisites;
pair<int,int> cur;
cur.first=0;
cur.second=1;
prerequisites.push_back(cur);
Solution s;
cout<<s.canFinish(2, prerequisites)<<endl;
return 0;
}
【注】可以看到利用Kahn算法进行环路检测的做法时间复杂度较高,可以考虑换成DFS的方法。这点在leetcode的题目中也有说明。
Hints:
- This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
- Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort.
- Topological sort could also be done via BFS.