Skip to content

Commit d268cb3

Browse files
authored
Create DetectCycleInDirectedGraph.java
Find cycles in directed graph
1 parent 04b1daf commit d268cb3

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed

DetectCycleInDirectedGraph.java

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
package ds.algo.solution;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
public class DetectCycleInDirectedGraph {
7+
8+
public static void main(String[] args) {
9+
Node one = new Node(1);
10+
Node two = new Node(2);
11+
Node three = new Node(3);
12+
Node four = new Node(4);
13+
Node five = new Node(5);
14+
Node six = new Node(6);
15+
16+
one.addChild(two).addChild(three).addChild(four);
17+
two.addChild(three);
18+
four.addChild(five);
19+
five.addChild(six);
20+
six.addChild(four);// this creates the cycle in the graph
21+
22+
Set<Node> nodes = new HashSet<>();
23+
nodes.add(one);
24+
nodes.add(two);
25+
nodes.add(three);
26+
nodes.add(four);
27+
nodes.add(five);
28+
nodes.add(six);
29+
30+
System.out.println(new DetectCycleInDirectedGraph().isCyclePresent(nodes));
31+
}
32+
33+
public boolean isCyclePresent(Set<Node> nodes) {
34+
35+
Set<Node> whiteSet = new HashSet<>(nodes);
36+
Set<Node> greySet = new HashSet<>();
37+
Set<Node> blackSet = new HashSet<>();
38+
39+
while (!whiteSet.isEmpty()) {
40+
if(inspectNode(whiteSet.iterator().next(), whiteSet, greySet, blackSet)) {
41+
return true;
42+
}
43+
}
44+
45+
return false;
46+
}
47+
48+
private boolean inspectNode(Node n, Set<Node> whiteSet, Set<Node> greaySet, Set<Node> blackSet) {
49+
50+
move(n, whiteSet, greaySet);
51+
52+
for (Node node : n.getChildren()) {
53+
if (blackSet.contains(node)) {
54+
continue;
55+
}
56+
if (greaySet.contains(node)) {
57+
return true;
58+
}
59+
if (inspectNode(node, whiteSet, greaySet, blackSet)) {
60+
return true;
61+
}
62+
}
63+
move(n, greaySet, blackSet);
64+
65+
return false;
66+
}
67+
68+
private void move(Node n, Set<Node> source, Set<Node> destination) {
69+
source.remove(n);
70+
destination.add(n);
71+
}
72+
}
73+
74+
class Node {
75+
76+
int value;
77+
78+
Set<Node> children;
79+
80+
Node(int val) {
81+
this.children = new HashSet<Node>();
82+
this.value = val;
83+
}
84+
85+
public Node addChild(Node n) {
86+
children.add(n);
87+
return this;
88+
}
89+
90+
public Set<Node> getChildren(){
91+
return children;
92+
}
93+
94+
@Override
95+
public String toString() {
96+
return String.valueOf(this.value);
97+
}
98+
}

0 commit comments

Comments
 (0)