-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleDetection.java
More file actions
44 lines (39 loc) · 1.21 KB
/
Copy pathCycleDetection.java
File metadata and controls
44 lines (39 loc) · 1.21 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
import java.util.ArrayList;
public class CycleDetection {
static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) {
// for undirected connect u and v and then v and u
adj.get(u).add(v);
adj.get(v).add(u);
}
static boolean DFSRec(ArrayList<ArrayList<Integer>> adj, int s, boolean[] mark, int parent) {
mark[s] = true;
// System.out.print(s + ",");
for(int u : adj.get(s)) {
if(mark[u] == false) {
if(DFSRec(adj, u, mark, -1) == true) {
return true;
}
}
else if(u != parent) {
return true;
}
}
return false;
}
static boolean DFS(ArrayList<ArrayList<Integer>> adj, int V) {
boolean[] mark = new boolean[V];
for(int i = 0; i < V; i++) {
mark[i] = false;
}
for(int i = 0; i < V; i++) {
if(mark[i] == false) {
if(DFSRec(adj, V, mark, i) == true) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
}
}