-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Detect Cycle in Directed Graph using DFS Algo
- Loading branch information
1 parent
d200c87
commit c05812e
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
#include<bits/stdc++.h> | ||
using namespace std; | ||
|
||
class Solution | ||
{ | ||
public: | ||
bool cycleDFS(int node,vector<int> adj[], vector<int> &vis, vector<int> &dfsvis) | ||
{ | ||
vis[node]=1; | ||
dfsvis[node]=1; | ||
|
||
for(auto it:adj[node]) | ||
{ | ||
if(!vis[it]) | ||
{ | ||
if(cycleDFS(it,adj,vis,dfsvis))return true; | ||
} | ||
else if(dfsvis[it]) | ||
return true; | ||
} | ||
dfsvis[node]=0; | ||
return false; | ||
} | ||
public: | ||
//Function to detect cycle in a directed graph. | ||
bool isCyclic(int V, vector<int> adj[]) | ||
{ | ||
vector<int>vis(V,0); | ||
vector<int>dfsvis(V,0); | ||
for(int i=0;i<V;i++) | ||
{ | ||
if(!vis[i]) | ||
{ | ||
if(cycleDFS(i,adj,vis,dfsvis)) | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
|
||
}; | ||
|
||
int main() | ||
{ | ||
|
||
int t; | ||
cin >> t; | ||
while(t--) | ||
{ | ||
int V, E; | ||
cin >> V >> E; | ||
|
||
vector<int> adj[V]; | ||
|
||
for(int i = 0; i < E; i++) | ||
{ | ||
int u, v; | ||
cin >> u >> v; | ||
adj[u].push_back(v); | ||
} | ||
|
||
Solution obj; | ||
cout << obj.isCyclic(V, adj) << "\n"; | ||
} | ||
|
||
return 0; | ||
} |