MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / topoSort

Method topoSort

Kahn'sAlgorithm.java:4–42  ·  view source on GitHub ↗
(int V, ArrayList<ArrayList<Integer>> adj)

Source from the content-addressed store, hash-verified

2{
3 //Function to return list containing vertices in Topological order.
4 static int[] topoSort(int V, ArrayList<ArrayList<Integer>> adj)
5 {
6 // add your code here
7 int indegree[] = new int[V]; //0
8 for(int u=0;u<adj.size();u++){
9 for(int v : adj.get(u)){
10 indegree[v]++;
11 }
12 }
13 Queue<Integer> queue = new LinkedList<>();
14 for(int i=0;i<V;i++){
15 if(indegree[i]==0){
16 queue.offer(i);
17 }
18 }
19 //3
20
21 ArrayList<Integer> res = new ArrayList<>();
22 while(!queue.isEmpty()){
23 int node = queue.poll();
24 res.add(node);
25 for(int neighbour : adj.get(node)){
26 indegree[neighbour]--;
27 if(indegree[neighbour]==0){
28 queue.offer(neighbour);
29 }
30 }
31 }
32
33 if(res.size() != V){
34 return new int[V];
35 }
36
37 int ans[] = new int[V];
38 for(int i=0;i<V;i++){
39 ans[i] = res.get(i);
40 }
41 return ans;
42 }
43}

Callers

nothing calls this directly

Calls 2

isEmptyMethod · 0.45
addMethod · 0.45

Tested by

no test coverage detected