-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSort.java
More file actions
88 lines (62 loc) · 1.82 KB
/
TopologicalSort.java
File metadata and controls
88 lines (62 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.util.*;
import java.io.*;
// Implement Topological Sorting
// Setting up the edges
class Edge{
int src,dest;
public Edge(int source, int dest){
this.src = source;
this.dest = dest;
}
}
// Class for initializing the graph
class Graph{
List<List<Integer>> list;
public Graph(List<Edge> edges, int size){
list = new ArrayList<>();
for(int i=0;i<size; i++){
list.add(new ArrayList<>());
}
for(Edge e: edges){
list.get(e.src).add(e.dest);
}
}
}
public class TopologicalSort {
static ArrayList<Integer> visited;
static Stack<Integer> result;
static void dfs(Graph graph, int currNode){
if(visited.contains(currNode)) return;
visited.add(currNode);
for(int vertex: graph.list.get(currNode)){
dfs(graph, currNode);
}
result.push(currNode);
}
static void topoSort(Graph graph, int nodeCount){
visited = new ArrayList<>();
result = new Stack<>();
for(int i=0; i<nodeCount; i++){
if(!visited.contains(i)){
dfs(graph, i);
}
}
while(!result.isEmpty()){
System.out.println(result.pop() + " ");
}
}
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
ArrayList<Edge> edge = new ArrayList<>();
System.out.println("Enter number of nodes: ");
int nodes = scan.nextInt();
System.out.println("Enter number of edges: ");
int edges = scan.nextInt();
for(int i=0; i<edges; i++){
edge.add(new Edge(scan.nextInt(), scan.nextInt()));
}
Graph graph = new Graph(edge, nodes);
topoSort(graph, nodes);
scan.close();
}
}