-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathcycleDetectionBfs.java
More file actions
52 lines (40 loc) · 1.14 KB
/
Copy pathcycleDetectionBfs.java
File metadata and controls
52 lines (40 loc) · 1.14 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package Graphs;
import java.util.*;
public class cycleDetectionBfs {
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
boolean vis[] = new boolean[V + 1];
boolean res = false;
for (int i = 1; i <= V; i++) {
if (vis[i] == false) {
res = isCycleDetected(i, vis, adj);
}
}
return res;
}
public boolean isCycleDetected(int n, boolean vis[], ArrayList<ArrayList<Integer>> adj) {
Queue<Pair> q = new LinkedList<>();
q.add(new Pair(n, -1));
vis[n] = true;
while (!q.isEmpty()) {
int node = q.peek().node;
int par = q.peek().prev;
q.remove();
for (Integer it : adj.get(node)) {
if (vis[it] == false) {
q.add(new Pair(it, node));
vis[it] = true;
} else if (it != par) {
return true;
}
}
}
return false;
}
}
class Pair {
int node, prev;
public Pair(int node, int prev) {
this.node = node;
this.prev = prev;
}
}