generated from zeikar/issueage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild-a-matrix-with-conditions.py
54 lines (40 loc) · 1.47 KB
/
build-a-matrix-with-conditions.py
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
class Solution:
def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]:
rowGraph = defaultdict(list)
rowIndegree = [0] * (k + 1)
colGraph = defaultdict(list)
colIndegree = [0] * (k + 1)
for rc in rowConditions:
rowGraph[rc[0]].append(rc[1])
rowIndegree[rc[1]] += 1
for cc in colConditions:
colGraph[cc[0]].append(cc[1])
colIndegree[cc[1]] += 1
def topologicalSort(graph, indegree):
ret = []
queue = deque()
for i in range(1, k + 1):
if indegree[i] == 0:
queue.append(i)
# cycle!
if len(queue) == 0:
return ret
while len(queue) > 0:
node = queue.popleft()
ret.append(node)
for next in graph[node]:
indegree[next] -= 1
if indegree[next] == 0:
queue.append(next)
return ret
rowsort = topologicalSort(rowGraph, rowIndegree)
colsort = topologicalSort(colGraph, colIndegree)
if len(rowsort) != k or len(colsort) != k:
return []
rpos = [0] * (k+1)
for i, r in enumerate(rowsort):
rpos[r] = i
ans = [[0] * k for _ in range(k)]
for i, c in enumerate(colsort):
ans[rpos[c]][i] = c
return ans