Skip to content

Commit 41d5748

Browse files
committed
added cycle detection in directed graph program
1 parent 20e9877 commit 41d5748

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// Java Program to detect cycle in a graph
2+
import java.util.ArrayList;
3+
import java.util.LinkedList;
4+
import java.util.List;
5+
6+
class Graph {
7+
8+
private final int V;
9+
private final List<List<Integer>> adj;
10+
11+
public Graph(int V)
12+
{
13+
this.V = V;
14+
adj = new ArrayList<>(V);
15+
16+
for (int i = 0; i < V; i++)
17+
adj.add(new LinkedList<>());
18+
}
19+
20+
private boolean isCyclicUtil(int i, boolean[] visited,
21+
boolean[] recStack)
22+
{
23+
24+
// Mark the current node as visited and
25+
// part of recursion stack
26+
if (recStack[i])
27+
return true;
28+
29+
if (visited[i])
30+
return false;
31+
32+
visited[i] = true;
33+
34+
recStack[i] = true;
35+
List<Integer> children = adj.get(i);
36+
37+
for (Integer c: children)
38+
if (isCyclicUtil(c, visited, recStack))
39+
return true;
40+
41+
recStack[i] = false;
42+
43+
return false;
44+
}
45+
46+
private void addEdge(int source, int dest) {
47+
adj.get(source).add(dest);
48+
}
49+
50+
// Returns true if the graph contains a
51+
// cycle, else false.
52+
private boolean isCyclic()
53+
{
54+
55+
// Mark all the vertices as not visited and
56+
// not part of recursion stack
57+
boolean[] visited = new boolean[V];
58+
boolean[] recStack = new boolean[V];
59+
60+
61+
// Call the recursive helper function to
62+
// detect cycle in different DFS trees
63+
for (int i = 0; i < V; i++)
64+
if (isCyclicUtil(i, visited, recStack))
65+
return true;
66+
67+
return false;
68+
}
69+
70+
public static void main(String[] args)
71+
{
72+
Graph graph = new Graph(4);
73+
graph.addEdge(0, 1);
74+
graph.addEdge(0, 2);
75+
graph.addEdge(1, 2);
76+
graph.addEdge(2, 0);
77+
graph.addEdge(2, 3);
78+
graph.addEdge(3, 3);
79+
80+
if(graph.isCyclic())
81+
System.out.println("Graph contains cycle");
82+
else
83+
System.out.println("Graph doesn't "
84+
+ "contain cycle");
85+
}
86+
}

0 commit comments

Comments
 (0)