[AlgoExpert] Cycle In Graph

Cycle In Graph

  • Time : O(v + e)
  • Space : O(v)
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;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/16/PS/AlgoExpert/cycle-in-graph/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.