判断一个图是否有环
https://www.cnblogs.com/tenosdoit/p/3644225.html
拓扑排序
https://www.cnblogs.com/nycsde/p/13683163.html
https://www.cxyxiaowu.com/1084.html
题解
https://www.cnblogs.com/grandyang/p/4484571.html
207
class Solution { public: bool canFinish(int numCourses, vector<vector<int>>& prerequisites) { if(numCourses<2||prerequisites.size()<2){ return true; } vector<vector<int>> graph(numCourses, vector<int>()); //入度个数 vector<int> in(numCourses); //初始化为有向邻接表 for (auto a : prerequisites) { graph[a[1]].push_back(a[0]); ++in[a[0]]; } //directed acycle graph,这里不用存 queue<int> dag; //将入度为0的加入dag for(int i=0;i<numCourses;++i){ if (in[i] == 0) dag.push(i); } int tmp; while(!dag.empty()){ tmp=dag.front();//取出第一个 dag.pop();//从dag中删除第一个 for(auto a : graph[tmp]){ --in[a]; if(in[a]==0){ dag.push(a); } } } //还有入度大于0的则有环 for(int i=0;i<numCourses;++i){ if (in[i] >0) return false; } return true; } };
210
class Solution { public: vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) { vector<int> dag; if(numCourses<2){ dag.push_back(0); return dag; } vector<vector<int>> graph(numCourses, vector<int>()); //入度个数 vector<int> in(numCourses); //初始化为有向邻接表 for (auto a : prerequisites) { graph[a[1]].push_back(a[0]); ++in[a[0]]; } //directed acycle graph,这里不用存 queue<int> q; //将入度为0的加入dag for(int i=0;i<numCourses;++i){ if (in[i] == 0) { q.push(i); } } int tmp; while(!q.empty()){ tmp=q.front();//取出第一个 dag.push_back(tmp); q.pop();//从dag中删除第一个 for(auto a : graph[tmp]){ --in[a]; if(in[a]==0){ q.push(a); } } } //dag元素个数不等于图中顶点个数则有环 if (dag.size() != numCourses) dag.clear(); return dag; } };
310
class Solution { //取剩下小于等于2时的节点 public: vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) { if (n == 1) return {0}; vector<vector<int>> graph(n, vector<int>()); //入度个数 vector<int> in(n); //初始化为有向邻接表 for (auto a : edges) { graph[a[1]].push_back(a[0]); graph[a[0]].push_back(a[1]); ++in[a[0]]; ++in[a[1]]; } //directed acycle graph,这里不用存 queue<int> q; //将入度为0的加入dag for(int i=0;i<n;++i){ if (in[i] == 1) { q.push(i); } } int tmp; vector<int> dag; int len; while(n>2){ len=q.size(); n-=len; for(int i=0;i<len;++i){ tmp=q.front();//取出第一个 q.pop();//从dag中删除第一个 for(auto a : graph[tmp]){ --in[a]; if(in[a]==1){ q.push(a); } } } } while(!q.empty()){ dag.push_back(q.front()); q.pop(); } return dag; } };