-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopologicalSortBFS.java
54 lines (43 loc) · 1.35 KB
/
TopologicalSortBFS.java
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
package Graphs;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class TopologicalSortBFS {
private static List<Integer> bfs(ArrayList<ArrayList<Integer>> adjList, int[] inDegree){
Queue<Integer> queue = new LinkedList<>();
List<Integer> topoSort = new ArrayList<>();
for (int i =0; i <inDegree.length; i++){
if(inDegree[i] == 0)
queue.add(i);
}
while (!queue.isEmpty()){
int node = queue.poll();
topoSort.add(node);
for (int v: adjList.get(node)){
inDegree[v]--;
if(inDegree[v] == 0)
queue.add(v);
}
}
return topoSort;
}
public static void main(String[] args){
int N = 6;
Graph g = new Graph(N);
g.addDirectedEdge(2,3);
g.addDirectedEdge(3, 1);
g.addDirectedEdge(4, 0);
g.addDirectedEdge(4, 1);
g.addDirectedEdge(5, 0);
g.addDirectedEdge(5, 2);
ArrayList<ArrayList<Integer>> adjList = Graph.getAdj();
int[] inDegree = new int[N];
for (int i =0; i < N ; i++){
for(int edge: adjList.get(i)){
inDegree[edge]++;
}
}
bfs(adjList, inDegree).forEach(System.out::println);
}
}