-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBuild_a_Matrix_With_Conditions.java
More file actions
81 lines (70 loc) · 2.55 KB
/
Build_a_Matrix_With_Conditions.java
File metadata and controls
81 lines (70 loc) · 2.55 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
71
72
73
74
75
76
77
78
79
80
81
import java.util.*;
import java.io.*;
import java.lang.*;
public class Build_a_Matrix_With_Conditions {
class Solution {
public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
List<Integer>[] rowGraph = new ArrayList[k + 1];
for(int i = 1 ; i < rowGraph.length; i ++) {
rowGraph[i] = new ArrayList();
}
for(int [] rowCondition : rowConditions){
rowGraph[rowCondition[0]].add(rowCondition[1]);
}
List<Integer>[] colGraph = new ArrayList[k + 1];
for(int i = 1 ; i < colGraph.length; i ++) {
colGraph[i] = new ArrayList();
}
for(int [] colCondition : colConditions){
colGraph[colCondition[0]].add(colCondition[1]);
}
int[] visited = new int[k + 1];
Deque<Integer> queue = new LinkedList<>();
for(int i = 1; i < rowGraph.length; i++){
if(!topSort(rowGraph, i, visited, queue)){
return new int[0][0];
}
}
int[] rowIndexMap = new int[k + 1];
for(int i = 0; i < k; i++){
int node = queue.pollLast();
rowIndexMap[node] = i;
}
visited = new int[k + 1];
queue = new LinkedList();
for(int i = 1; i < colGraph.length; i++){
if(!topSort(colGraph, i, visited, queue)){
return new int[0][0];
}
}
int[] colOrder = new int[k];
int[] colIndexMap = new int[k+1];
for(int i = 0; i < k; i++){
int node = queue.pollLast();
colOrder[i] = node;
colIndexMap[node] = i;
}
int[][] result = new int[k][k];
for(int i = 1; i <= k; i++){
result[rowIndexMap[i]][colIndexMap[i]] = i;
}
return result;
}
public boolean topSort(List<Integer>[] graph, int node, int[] visited, Deque<Integer> queue){
if(visited[node] == 2) {
return false;
}
if(visited[node] == 0){
visited[node] = 2;
for(int child : graph[node]){
if(!topSort(graph, child, visited, queue)){
return false;
}
}
visited[node] = 1;
queue.add(node);
}
return true;
}
}
}