-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathBuildAMatrixWithConditions.java
More file actions
70 lines (66 loc) · 1.91 KB
/
BuildAMatrixWithConditions.java
File metadata and controls
70 lines (66 loc) · 1.91 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Solution {
int[] topoSort(int V, int pairs[][])
{
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i=0;i<=V;i++){
adj.add(new ArrayList<>());
}
for(int pair[] : pairs){
int u = pair[0];
int v = pair[1];
adj.get(u).add(v);
}
// add your code here
int indegree[] = new int[V+1]; //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=1;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[0];
}
int ans[] = new int[V];
for(int i=0;i<V;i++){
ans[i] = res.get(i);
}
return ans;
}
public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
int rowToposort[] = topoSort(k, rowConditions);
if(rowToposort.length==0){
return new int[0][0];
}
int colToposort[] = topoSort(k, colConditions);
if(colToposort.length==0){
return new int[0][0];
}
int matrix[][] = new int[k][k];
for(int i=0;i<k;i++){
for(int j=0;j<k;j++){
if(rowToposort[i] == colToposort[j]){
matrix[i][j] = colToposort[j];
}
}
}
return matrix;
}
}