-
Notifications
You must be signed in to change notification settings - Fork 0
/
build-a-matrix-with-conditions.go
64 lines (57 loc) · 1.2 KB
/
build-a-matrix-with-conditions.go
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
package leetcode_solutions_golang
import (
"fmt"
)
func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int {
orderByRow, err := buildTopologicalSort(k, rowConditions)
if err != nil {
return [][]int{}
}
orderByCol, err := buildTopologicalSort(k, colConditions)
if err != nil {
return [][]int{}
}
matrix := make([][]int, k)
for i := 0; i < k; i++ {
matrix[i] = make([]int, k)
for j := 0; j < k; j++ {
if orderByRow[i] == orderByCol[j] {
matrix[i][j] = orderByRow[i]
}
}
}
return matrix
}
func buildTopologicalSort(nNode int, edge [][]int) ([]int, error) {
graph := make(map[int][]int)
inDegree := make(map[int]int)
for i := 0; i < len(edge); i++ {
graph[edge[i][0]] = append(graph[edge[i][0]], edge[i][1])
inDegree[edge[i][1]]++
}
order := make([]int, 0)
for {
next := -1
isCompleted := true
for i := 1; i <= nNode; i++ {
if inDegree[i] >= 0 {
isCompleted = false
}
if inDegree[i] == 0 {
next = i
break
}
}
if isCompleted {
return order, nil
}
if next == -1 {
return nil, fmt.Errorf("cycle detected")
}
order = append(order, next)
inDegree[next] = -1
for _, v := range graph[next] {
inDegree[v]--
}
}
}