-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathTopologicalSort.java
More file actions
74 lines (56 loc) · 1.91 KB
/
TopologicalSort.java
File metadata and controls
74 lines (56 loc) · 1.91 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
package sortingAlgorithms;
import java.util.*;
// Problem Statement => Find a topological sequence of a directed acyclic graph.
public class TopologicalSort {
// Vertices
private final int V;
// Adjacency List
private final ArrayList<ArrayList<Integer> > adj;
// Constructor
TopologicalSort(int v){
V = v;
adj = new ArrayList<>(v);
for(int i = 0; i < v; i++)
adj.add(new ArrayList<>());
}
// Function to add an edge into the graph
void addEdge(int v, int w){
adj.get(v).add(w);
}
// A recursive function to add an edge into the graph
void topological_Order_Util(int v, boolean[] visited, Stack<Integer> stack){
visited[v] = true;
Integer i;
for (Integer integer : adj.get(v)) {
i = integer;
if (!visited[i])
topological_Order_Util(i, visited, stack);
}
stack.push(v);
}
void topological_Order() {
Stack<Integer> stack = new Stack<>();
boolean[] visited = new boolean[V];
for(int i = 0; i < V; i++)
if(!visited[i])
topological_Order_Util(i, visited, stack);
while(!stack.empty())
System.out.print(stack.pop() + " ");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter how many number of edges you want to enter: ");
int number = sc.nextInt();
System.out.print("Enter the vertice name: ");
int v = sc.nextInt();
System.out.print("Enter weight of vertice: ");
int w = sc.nextInt();
TopologicalSort g = new TopologicalSort(v);
for(int i = 0; i < number; i++)
g.addEdge(v, w);
System.out.println("Following is a Topological " + "sort of the given graph");
sc.close();
// Function Call
g.topological_Order();
}
}