- Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTopologicalSortingDFS.java
More file actions
Latest commit
71 lines (60 loc) · 2.95 KB
/
Copy pathTopologicalSortingDFS.java
File metadata and controls
71 lines (60 loc) · 2.95 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
packageGraph;
importjava.util.ArrayList;
importjava.util.Scanner;
importjava.util.Stack;
publicclassTopologicalSortingDFS {
publicstaticvoidmain(String[] args) {
Scannersc = newScanner(System.in);
ArrayList<ArrayList<Integer>> adjacencyList = newArrayList<>();
// Taking input for number of nodes
System.out.println("Enter the number of nodes:");
intnumberOfNodes = sc.nextInt();
// initializing adjacencyList with new ArrayList<>()
for(inti=1 ; i<=numberOfNodes+1 ; i++){
adjacencyList.add(newArrayList<>());
}
// taking input of adjacent nodes of particular node
for(inti=1 ; i<=numberOfNodes ; i++){
System.out.println("Enter number of adjacent nodes to the node : " + i);
intcountOfAdjacentNodes = sc.nextInt();
// taking input of the particular adjacent nodes to the node i
System.out.println("Enter adjacent nodes:");
for(intj=0 ; j<countOfAdjacentNodes ; j++){
// taking input of adjacent node
intadjacentNode = sc.nextInt();
// adding the adjacent node to the particular node i
adjacencyList.get(i).add(adjacentNode);
}
}
// This is a helper method which is used to call to topologicalSort method
// for printing the topological sort of the given graph
helperMethod(adjacencyList, numberOfNodes);
}
publicstaticvoidhelperMethod(ArrayList<ArrayList<Integer>> adjacencyList, intnumberOfNodes){
boolean[] visitedNodes = newboolean[numberOfNodes+1]; // visited array
Stack<Integer> stack = newStack<>(); // Stack data structure for storing topological sorting
// Run loop for all nodes
for(intnode=1 ; node<=numberOfNodes ; node++){
// If not visited then call for topologicalSort method
if(!visitedNodes[node]){
topologicalSort(node, adjacencyList, visitedNodes, stack);
}
}
// Topological sorting of the given graph is printed here
System.out.println("Topological sorting of the given graph is :");
while(!stack.isEmpty()){
System.out.print(stack.pop() + " ");
}
}
publicstaticvoidtopologicalSort(intnode, ArrayList<ArrayList<Integer>> adjacencyList, boolean[] visitedNodes, Stack<Integer> stack){
visitedNodes[node] = true; // mark the current node visited
// now check for all adjacent nodes of the current node
for(intadjacentNode : adjacencyList.get(node)){
// if not visited then call method
if(!visitedNodes[adjacentNode]){
topologicalSort(adjacentNode, adjacencyList, visitedNodes, stack);
}
}
stack.add(node); // at last add the current node into the stack data structure
}
}