-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdetect cycle using dfs
31 lines (27 loc) · 988 Bytes
/
detect cycle using dfs
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
29
30
31
import java.util.List;
public class Solution {
static class Graph {
boolean dfs(int node, int parent, List<List<Integer>> adj, boolean[] vis) {
vis[node] = true;
for (int neighbor : adj.get(node)) {
if (!vis[neighbor]) {
if (dfs(neighbor, node, adj, vis)) {
return true; // Cycle detected
}
} else if (neighbor != parent) {
return true; // Back edge found, indicating a cycle
}
}
return false; // No cycle found in this DFS traversal
}
boolean detectCycle(int v, List<List<Integer>> adj) {
boolean[] vis = new boolean[v];
for (int i = 0; i < v; i++) {
if (!vis[i] && dfs(i, -1, adj, vis)) {
return true; // Cycle detected
}
}
return false; // No cycle found
}
}
}