forked from chetannihith/Java-hacktoberfest25
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCycleDetectionPrt.java
More file actions
59 lines (48 loc) · 1.82 KB
/
CycleDetectionPrt.java
File metadata and controls
59 lines (48 loc) · 1.82 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
53
54
55
56
57
58
59
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CycleDetectionPrt {
public static void main(String[] args) {
Map<Integer, List<Integer>> graph = new HashMap<>();
graph.put(0, List.of(1, 2));
graph.put(1, List.of(2));
graph.put(2, List.of(0, 3));
graph.put(3, List.of(3));
if (containsCycle(graph)) {
System.out.println("The graph contains a cycle.");
} else {
System.out.println("The graph does not contain a cycle.");
}
}
public static boolean containsCycle(Map<Integer, List<Integer>> graph) {
//track of visited vertices during DFS
boolean[] visited = new boolean[graph.size()];
// track of vertices in the current DFS traversal
boolean[] currentlyInStack = new boolean[graph.size()];
for (int vertex : graph.keySet()) {
if (!visited[vertex] && isCyclic(graph, vertex, visited, currentlyInStack)) {
return true;
}
}
return false;
}
private static boolean isCyclic(Map<Integer, List<Integer>> graph, int vertex,
boolean[] visited, boolean[] currentlyInStack) {
visited[vertex] = true;
currentlyInStack[vertex] = true;
if (graph.containsKey(vertex)) {
for (int neighbor : graph.get(vertex)) {
if (!visited[neighbor]) {
if (isCyclic(graph, neighbor, visited, currentlyInStack)) {
return true;
}
} else if (currentlyInStack[neighbor]) {
return true; //Cycle detected
}
}
}
currentlyInStack[vertex] = false; //Backtrack
return false;
}
}