-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCycle_Detection.java
More file actions
28 lines (27 loc) · 847 Bytes
/
Cycle_Detection.java
File metadata and controls
28 lines (27 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
// Function to detect cycle in an undirected graph.
public boolean isCycle(ArrayList<ArrayList<Integer>> adj) {
// Code here
int vis[]=new int[V];
for (int i = 0; i < V; i++) {
if (!vis[i]) { // If node is unvisited, start DFS
if (dfs(i, -1, vis, adj))
return true;
}
}
return false;
}
}
boolean dfs(ArrayList<ArrayList<Integer>> adj, int node, int parent, int vis[]){
vis[node]=1;
for(int adjacentNode: adj.get(node)) {
if(vis[adjacentNode]==0) {
if(dfs(adjacentNode, node, vis, adj) == true)
return true;
}
else if(adjacentNode != parent)
return true;
}
return false;
}
}