1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| bool dfs(int u, int root, vector<vector<int>>& adj, vector<int>& seen, vector<int>& vis) { if(seen[u] == root) return true; if(vis[u] != -1) return false; vis[u] = root; seen[u] = root; for(auto& v : adj[u]) { if(dfs(v, root, adj, seen, vis)) return true; } seen[u] = -1; return false; } bool cycleInGraph(vector<vector<int>> edges) { int n = edges.size(); vector<int> seen(n, -1), vis(n, -1); for(int i = 0; i < n; i++) { if(vis[i] != -1) continue; if(dfs(i,i,edges,seen, vis)) return true; } return false; }
|