-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathKahn'sAlgorithm.java
More file actions
43 lines (40 loc) · 1.11 KB
/
Kahn'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
class Solution
{
//Function to return list containing vertices in Topological order.
static int[] topoSort(int V, ArrayList<ArrayList<Integer>> adj)
{
// add your code here
int indegree[] = new int[V]; //0
for(int u=0;u<adj.size();u++){
for(int v : adj.get(u)){
indegree[v]++;
}
}
Queue<Integer> queue = new LinkedList<>();
for(int i=0;i<V;i++){
if(indegree[i]==0){
queue.offer(i);
}
}
//3
ArrayList<Integer> res = new ArrayList<>();
while(!queue.isEmpty()){
int node = queue.poll();
res.add(node);
for(int neighbour : adj.get(node)){
indegree[neighbour]--;
if(indegree[neighbour]==0){
queue.offer(neighbour);
}
}
}
if(res.size() != V){
return new int[V];
}
int ans[] = new int[V];
for(int i=0;i<V;i++){
ans[i] = res.get(i);
}
return ans;
}
}