Skip to content

Commit b612a7d

Browse files
committed
topological sort implementation, DFS based approach
1 parent 25614e0 commit b612a7d

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package Graph;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
6+
public class TopologicalSorting {
7+
8+
public static void main(String[] args) {
9+
10+
int totalVertices = 6; // test graph 1
11+
// int totalVertices = 3; // test graph 2
12+
ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>(totalVertices);
13+
for (int i = 0; i < totalVertices; i++) {
14+
adjList.add(new ArrayList<Integer>(i));
15+
}
16+
// test graph 1, output: 0 2 1 3 5 4
17+
addEdge(adjList, 0, 1);
18+
addEdge(adjList, 0, 2);
19+
addEdge(adjList, 1, 3);
20+
addEdge(adjList, 2, 3);
21+
addEdge(adjList, 3, 4);
22+
addEdge(adjList, 3, 5);
23+
24+
// test graph 2, output: 0 2 1
25+
// addEdge(adjList, 0, 1);
26+
// addEdge(adjList, 0, 2);
27+
28+
display(adjList);
29+
30+
System.out.println("\ntopological sorting...");
31+
topologicalSort(adjList);
32+
}
33+
34+
private static void addEdge(ArrayList<ArrayList<Integer>> adjList, int u, int v) {
35+
adjList.get(u).add(v); // directed graph Edge
36+
}
37+
38+
private static void display(ArrayList<ArrayList<Integer>> adjList) {
39+
for (int i = 0; i < adjList.size(); i++) {
40+
System.out.println(i + ": " + adjList.get(i));
41+
}
42+
}
43+
44+
// O(V+E) Time, DFS based approach
45+
public static void topologicalSort(ArrayList<ArrayList<Integer>> adjList) {
46+
// use addFirst() and removeFirst() method of LinkedList for O(1) Time
47+
LinkedList<Integer> stack = new LinkedList<>();
48+
49+
boolean[] visited = new boolean[adjList.size()];
50+
51+
for (int vtx = 0; vtx < adjList.size(); vtx++) {
52+
if (visited[vtx] == false) {
53+
dfsTraverse(adjList, vtx, stack, visited);
54+
}
55+
}
56+
57+
while (!stack.isEmpty()) {
58+
System.out.print(stack.removeFirst() + " "); // pop
59+
}
60+
}
61+
62+
private static void dfsTraverse(ArrayList<ArrayList<Integer>> adjList, int vertex, LinkedList<Integer> stack,
63+
boolean[] visited) {
64+
65+
visited[vertex] = true;
66+
67+
for (Integer neighbor : adjList.get(vertex)) {
68+
if (visited[neighbor] == false) {
69+
dfsTraverse(adjList, neighbor, stack, visited);
70+
}
71+
}
72+
stack.addFirst(vertex); // push
73+
}
74+
}

0 commit comments

Comments
Β (0)