mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «2392. Build a Matrix With Conditions»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
fa59e60f35
commit
c911ab1f19
1 changed files with 68 additions and 0 deletions
68
go/build-a-matrix-with-conditions.go
Normal file
68
go/build-a-matrix-with-conditions.go
Normal file
|
@ -0,0 +1,68 @@
|
|||
package main
|
||||
|
||||
import aq "github.com/emirpasic/gods/v2/queues/arrayqueue"
|
||||
|
||||
func buildMatrix(k int, rowConditions [][]int, colConditions [][]int) [][]int {
|
||||
toposort := func(edges [][]int, n int) []int {
|
||||
neighbours := make([][]int, n+1)
|
||||
for i := range n + 1 {
|
||||
neighbours[i] = []int{}
|
||||
}
|
||||
|
||||
degrees, order := make([]int, n+1), make([]int, n)
|
||||
for _, edge := range edges {
|
||||
u, v := edge[0], edge[1]
|
||||
|
||||
neighbours[u] = append(neighbours[u], v)
|
||||
degrees[v]++
|
||||
}
|
||||
|
||||
queue := aq.New[int]()
|
||||
for i := 1; i <= n; i++ {
|
||||
if degrees[i] == 0 {
|
||||
queue.Enqueue(i)
|
||||
}
|
||||
}
|
||||
|
||||
idx := 0
|
||||
for !queue.Empty() {
|
||||
u, _ := queue.Dequeue()
|
||||
order[idx] = u
|
||||
|
||||
n--
|
||||
for _, v := range neighbours[u] {
|
||||
degrees[v]--
|
||||
if degrees[v] == 0 {
|
||||
queue.Enqueue(v)
|
||||
}
|
||||
}
|
||||
|
||||
idx++
|
||||
}
|
||||
|
||||
if n != 0 {
|
||||
return []int{}
|
||||
}
|
||||
return order
|
||||
}
|
||||
|
||||
rowOrder, colOrder := toposort(rowConditions, k), toposort(colConditions, k)
|
||||
if len(rowOrder) == 0 || len(colOrder) == 0 {
|
||||
return [][]int{}
|
||||
}
|
||||
|
||||
matrix := make([][]int, k)
|
||||
for i := range k {
|
||||
matrix[i] = make([]int, k)
|
||||
}
|
||||
|
||||
for row := range k {
|
||||
for col := range k {
|
||||
if rowOrder[row] == colOrder[col] {
|
||||
matrix[row][col] = rowOrder[row]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matrix
|
||||
}
|
Loading…
Reference in a new issue