最近就是忙工作项目 工作间隙就刷了刷LEETCODE 所以没啥更新
1 // 1111111.cpp: 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <vector> 6 #include <queue> 7 8 using namespace std; 9 10 bool canFinish1(int numCourses, vector<vector<int>>& prerequisites) { 11 vector<vector<int> > graph(numCourses, vector<int>(0)); 12 vector<int> in(numCourses, 0); 13 for (auto a : prerequisites) { 14 graph[a[1]].push_back(a[0]); 15 ++in[a[0]]; 16 } 17 queue<int> q; 18 for (int i = 0; i < numCourses; ++i) { 19 if (in[i] == 0) q.push(i); 20 } 21 while (!q.empty()) { 22 int t = q.front(); 23 q.pop(); 24 for (auto a : graph[t]) { 25 --in[a]; 26 if (in[a] == 0) q.push(a); 27 } 28 } 29 for (int i = 0; i < numCourses; ++i) { 30 if (in[i] != 0) return false; 31 } 32 return true; 33 } 34 35 //========================================================================== 36 37 bool canFinishDFS(vector<vector<int> > &graph, vector<int> &visit, int i) { 38 if (visit[i] == -1) return false; 39 if (visit[i] == 1) return true; 40 visit[i] = -1; 41 for (auto a : graph[i]) { 42 if (!canFinishDFS(graph, visit, a)) return false; 43 } 44 visit[i] = 1; 45 return true; 46 } 47 48 bool canFinish2(int numCourses, vector<vector<int> >& prerequisites) { 49 vector<vector<int> > graph(numCourses, vector<int>(0)); 50 vector<int> visit(numCourses, 0); 51 for (auto a : prerequisites) { 52 graph[a[1]].push_back(a[0]); 53 } 54 for (int i = 0; i < numCourses; ++i) { 55 if (!canFinishDFS(graph, visit, i)) return false; 56 } 57 return true; 58 } 59 60 61 int main() 62 { 63 //测试数据 64 { 65 int i = 2; 66 vector<vector<int> > v; 67 v.push_back(std::vector<int>{0, 1}); 68 v.push_back(std::vector<int>{1 ,0}); 69 canFinish1(i , v); 70 } 71 //{ 72 // int i = 2; 73 // vector<vector<int> > v; 74 // v.push_back(std::vector<int>{1, 0}); 75 // v.push_back(std::vector<int>{0, 1}); 76 //} 77 //{ 78 // int i = 2; 79 // vector<vector<int> > v; 80 // v.push_back(std::vector<int>{1, 0}); 81 //} 82 //{ 83 // int i = 3; 84 // vector<vector<int> > v; 85 // v.push_back(std::vector<int>{1, 0}); 86 // v.push_back(std::vector<int>{2, 0}); 87 //} 88 89 // { 90 // int i = 3; 91 // vector<vector<int> > v; 92 // v.push_back(std::vector<int>{1, 0}); 93 // v.push_back(std::vector<int>{2, 0}); 94 // } 95 // 96 // { 97 // int i = 3; 98 // vector<vector<int> > v; 99 // v.push_back(std::vector<int>{0, 1}); 100 // v.push_back(std::vector<int>{1, 2}); 101 // } 102 // 103 // { 104 // int i = 4; 105 // vector<vector<int> > v; 106 // v.push_back(std::vector<int>{0, 1}); 107 // v.push_back(std::vector<int>{1, 2}); 108 // v.push_back(std::vector<int>{2, 0}); 109 // v.push_back(std::vector<int>{1, 3}); 110 // } 111 // 112 // { 113 // int i = 4; 114 // vector<vector<int> > v; 115 // v.push_back(std::vector<int>{0, 1}); 116 // v.push_back(std::vector<int>{1, 2}); 117 // v.push_back(std::vector<int>{1, 3}); 118 // } 119 120 121 122 123 return 0; 124 }