Skip to content

Commit f01f8be

Browse files
Added detect cycle in directed graph
1 parent e667f88 commit f01f8be

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
class Solution{
5+
private:
6+
/**
7+
* Detecting of cycle using DFS
8+
*/
9+
bool detectCycleUsingDFS(int node, vector<vector<int>>& adj, vector<int>& visited, vector<int>& pathVisited){
10+
visited[node] = 1;
11+
pathVisited[node] = 1;
12+
13+
for(auto it: adj[node]){
14+
if(!visited[it]){
15+
if(detectCycleUsingDFS(it, adj, visited, pathVisited)) return true;
16+
}else{
17+
// If the node has been previously visited but it has to be be visited on the same path
18+
if(pathVisited[it]){
19+
return true;
20+
}
21+
}
22+
}
23+
24+
pathVisited[node] = 0; // while moving backwards, making nodes as not path visited
25+
return false;
26+
}
27+
public:
28+
bool hasCycle(vector<vector<int>>& adj){
29+
int n = adj.size();
30+
vector<int> visited(n, 0);
31+
vector<int> pathVisited(n, 0);
32+
33+
for(int i=0 ; i<n ; i++){
34+
if(!visited[i]){
35+
if(detectCycleUsingDFS(i, adj, visited, pathVisited)) return true;
36+
}
37+
}
38+
return false;
39+
}
40+
};
41+
42+
int main() {
43+
int n = 10;
44+
vector<vector<int>> adj(n+1);
45+
/**
46+
* 1--> 2 -------> 3 --> 4
47+
* ^ | |
48+
* | v v
49+
* 8 <--10 7 --> 5 --> 6
50+
* \> />
51+
* 9
52+
*/
53+
54+
adj[1].push_back(2); // 1 -> 2
55+
56+
adj[2].push_back(3); // 2 -> 3
57+
58+
adj[3].push_back(4); // 3 -> 4
59+
adj[3].push_back(7); // 3 -> 7
60+
61+
adj[4].push_back(5); // 4 -> 5
62+
63+
adj[5].push_back(6); // 5 -> 6
64+
65+
adj[7].push_back(5); // 7 -> 5
66+
67+
adj[8].push_back(2); // 8 -> 2 (cycle)
68+
adj[8].push_back(9); // 8 -> 9
69+
70+
adj[9].push_back(10); // 9 -> 10
71+
72+
adj[10].push_back(8); // 10 -> 8 (cycle)
73+
74+
Solution sol;
75+
bool isCycle = sol.hasCycle(adj);
76+
cout << ( isCycle ? "The graph has cycle" : "The graph does not have a cycle" ) << endl;
77+
78+
return 0;
79+
}

0 commit comments

Comments
 (0)