1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include <iostream> #include <vector> #include <queue>
using namespace std;
int main() { vector<vector<int>> graph{ {1, 2}, {3}, {3}, {4}, {} }; vector<int> path; queue<int> q; q.push(0); vector<int> indegree(5, 0); for (auto i : graph) { for (auto j : i) { indegree[j]++; } } vector<bool> visited(5, false); bool isCircle = false; while (!q.empty()) { int size = q.size(); while (size--) { int cur = q.front(); if (visited[cur]) isCircle = true; visited[cur] = true; q.pop(); path.push_back(cur); for (auto neighbor : graph[cur]) { if (--indegree[neighbor] == 0) { q.push(neighbor); } } } } for (auto i : path) { cout << i << ' '; } cout << endl; cout << isCircle; return 0; }
|