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

Method topoSort

BuildAMatrixWithConditions.java:2–49  ·  view source on GitHub ↗
(int V, int pairs[][])

Source from the content-addressed store, hash-verified

1class Solution {
2 int[] topoSort(int V, int pairs[][])
3 {
4 ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
5 for(int i=0;i<=V;i++){
6 adj.add(new ArrayList<>());
7 }
8 for(int pair[] : pairs){
9 int u = pair[0];
10 int v = pair[1];
11 adj.get(u).add(v);
12 }
13 // add your code here
14 int indegree[] = new int[V+1]; //0
15 for(int u=0;u<adj.size();u++){
16 for(int v : adj.get(u)){
17 indegree[v]++;
18 }
19 }
20 Queue<Integer> queue = new LinkedList<>();
21 for(int i=1;i<=V;i++){
22 if(indegree[i]==0){
23 queue.offer(i);
24 }
25 }
26 //3
27
28 ArrayList<Integer> res = new ArrayList<>();
29 while(!queue.isEmpty()){
30 int node = queue.poll();
31 res.add(node);
32 for(int neighbour : adj.get(node)){
33 indegree[neighbour]--;
34 if(indegree[neighbour]==0){
35 queue.offer(neighbour);
36 }
37 }
38 }
39
40 if(res.size() != V){
41 return new int[0];
42 }
43
44 int ans[] = new int[V];
45 for(int i=0;i<V;i++){
46 ans[i] = res.get(i);
47 }
48 return ans;
49 }
50 public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
51 int rowToposort[] = topoSort(k, rowConditions);
52 if(rowToposort.length==0){

Callers 1

buildMatrixMethod · 0.95

Calls 2

addMethod · 0.45
isEmptyMethod · 0.45

Tested by

no test coverage detected