1.

Write a function to detect cycle in an undirected graph

Answer»


  • 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

From the above representation, we can see that there exists a cycle: 1→2→3→1

//function to run dfs for a given node in the graph
int dfs(int v,vector<int> adj[],vector<int> &visited,vector<int> &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<int> adj[]) {
vector<int> 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;
}


  • Time Complexity: O(V+E)


  • Space Complexity: O(V)




Discussion

No Comment Found