Skip to content

Commit 81b9d0e

Browse files
authored
Create TopologicalSort.java
1 parent d268cb3 commit 81b9d0e

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

TopologicalSort.java

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package ds.algo.solution;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
import java.util.Stack;
6+
7+
public class TopologicalSort {
8+
9+
public static void main(String[] args) {
10+
TopoNode a = new TopoNode("a");
11+
TopoNode b = new TopoNode("b");
12+
TopoNode c = new TopoNode("c");
13+
TopoNode d = new TopoNode("d");
14+
TopoNode e = new TopoNode("e");
15+
TopoNode f = new TopoNode("f");
16+
TopoNode g = new TopoNode("g");
17+
TopoNode h = new TopoNode("h");
18+
19+
a.addChild(c);
20+
b.addChild(c).addChild(d);
21+
c.addChild(e);
22+
d.addChild(f);
23+
e.addChild(f).addChild(h);
24+
f.addChild(g);
25+
26+
Set<TopoNode> nodes = new HashSet<>();
27+
nodes.add(a);
28+
nodes.add(b);
29+
nodes.add(c);
30+
nodes.add(d);
31+
nodes.add(e);
32+
nodes.add(f);
33+
nodes.add(g);
34+
35+
Stack<TopoNode> stack = new TopologicalSort().topoSort(nodes);
36+
while(!stack.isEmpty()) {
37+
System.out.println(stack.pop());
38+
}
39+
}
40+
41+
private Stack<TopoNode> topoSort(Set<TopoNode> nodes) {
42+
Stack<TopoNode> topoStack = new Stack<>();
43+
Set<TopoNode> visited = new HashSet<>();
44+
Set<TopoNode> allNodes = new HashSet<>(nodes);
45+
46+
for (TopoNode topoNode : allNodes) {
47+
sort(topoNode, topoStack, visited);
48+
}
49+
50+
return topoStack;
51+
}
52+
53+
private void sort(TopoNode node, Stack<TopoNode> topoStack, Set<TopoNode> visited) {
54+
if (visited.contains(node)) {
55+
return;
56+
}
57+
visited.add(node);
58+
for (TopoNode childNode : node.getChildren()) {
59+
sort(childNode, topoStack, visited);
60+
}
61+
topoStack.add(node);
62+
}
63+
}
64+
65+
class TopoNode {
66+
67+
String value;
68+
69+
Set<TopoNode> children;
70+
71+
TopoNode(String val) {
72+
this.children = new HashSet<TopoNode>();
73+
this.value = val;
74+
}
75+
76+
public TopoNode addChild(TopoNode n) {
77+
children.add(n);
78+
return this;
79+
}
80+
81+
public Set<TopoNode> getChildren(){
82+
return children;
83+
}
84+
85+
@Override
86+
public String toString() {
87+
return this.value;
88+
}
89+
}

0 commit comments

Comments
 (0)