-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFG Detect cycle in an undirected graph.java
70 lines (56 loc) · 1.83 KB
/
GFG Detect cycle in an undirected graph.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// BFS approach
class Solution {
private class Pair {
int node;
int parent;
Pair(int node, int parent) {
this.node = node;
this.parent = parent;
}
}
// Function to detect cycle in an undirected graph.
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
boolean[] vis = new boolean[V];
for (int i = 0; i < V; i++)
if (!vis[i])
if (bfs(i, adj, vis)) return true;
return false;
}
private boolean bfs(int cur, ArrayList<ArrayList<Integer>> adj, boolean[] vis) {
Queue<Pair> q = new LinkedList<>();
vis[cur] = true;
q.offer(new Pair(cur, -1));
while (!q.isEmpty()) {
int node = q.peek().node;
int parent = q.poll().parent;
for (int i: adj.get(node))
if (!vis[i]) {
vis[i] = true;
q.offer(new Pair(i, node));
} else if(i != parent)
return true;
}
return false;
}
}
// DFS Approach
class Solution {
// Function to detect cycle in an undirected graph.
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here
boolean[] vis = new boolean[V];
for (int i = 0; i < V; i++)
if (!vis[i])
if (dfs(i, -1, adj, vis)) return true;
return false;
}
private boolean dfs(int cur, int parent, ArrayList<ArrayList<Integer>> adj, boolean[] vis) {
if (vis[cur]) return true;
vis[cur] = true;
for (int i: adj.get(cur))
if (i != parent)
if(dfs(i, cur, adj, vis)) return true;
return false;
}
}