Aryan PrajapatKnowledge Contributor
Write a function to detect cycle in an undirected graph Input: n = 4, e = 4 , 0 1, 1 2, 2 3, 3 1 Output: Yes Explanation: The graph is represented as follows in adjacency list representation: 0->1 1->2 2->3 3->1
Write a function to detect cycle in an undirected graph Input: n = 4, e = 4 , 0 1, 1 2, 2 3, 3 1 Output: Yes Explanation: The graph is represented as follows in adjacency list representation: 0->1 1->2 2->3 3->1
//function to run dfs for a given node in the graph
int dfs(int v,vector adj[],vector &visited,vector &rec,int i,int parent){
int ans=0;
visited[i]=1;
rec[i]=1;
for(auto x : adj[i]){
if(x!=parent) {
if(rec[x])
return 1;
ans=dfs(v,adj,visited,rec,x,i);
if(ans)
return 1;
}
}
rec[i]=0;
return 0;
}
// Function to detect cycle in an undirected graph.
// it takes adjacency list representation as an argument
bool isCycle(int v, vector adj[]) {
vector visited(v,0),rec(v,0);
int ans=0;
for(int i=0;i<v;i++){
if(visited[i]==0)
ans=dfs(v,adj,visited,rec,i,-1);
if(ans)
return 1;
}
return 0;
}