- Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathKahn'sAlgorithm.java
More file actions
Latest commit
43 lines (40 loc) · 1.11 KB
/
Copy pathKahn'sAlgorithm.java
File metadata and controls
43 lines (40 loc) · 1.11 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
classSolution
{
//Function to return list containing vertices in Topological order.
staticint[] topoSort(intV, ArrayList<ArrayList<Integer>> adj)
{
// add your code here
intindegree[] = newint[V]; //0
for(intu=0;u<adj.size();u++){
for(intv : adj.get(u)){
indegree[v]++;
}
}
Queue<Integer> queue = newLinkedList<>();
for(inti=0;i<V;i++){
if(indegree[i]==0){
queue.offer(i);
}
}
//3
ArrayList<Integer> res = newArrayList<>();
while(!queue.isEmpty()){
intnode = queue.poll();
res.add(node);
for(intneighbour : adj.get(node)){
indegree[neighbour]--;
if(indegree[neighbour]==0){
queue.offer(neighbour);
}
}
}
if(res.size() != V){
returnnewint[V];
}
intans[] = newint[V];
for(inti=0;i<V;i++){
ans[i] = res.get(i);
}
returnans;
}
}