From c911ab1f19feeec699b6154e2e49afba5411f8c7 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 21 Jul 2024 23:13:29 +0200 Subject: [PATCH] =?UTF-8?q?go:=20add=20=C2=AB2392.=20Build=20a=20Matrix=20?= =?UTF-8?q?With=20Conditions=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- go/build-a-matrix-with-conditions.go | 68 ++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 go/build-a-matrix-with-conditions.go diff --git a/go/build-a-matrix-with-conditions.go b/go/build-a-matrix-with-conditions.go new file mode 100644 index 0000000..7101abe --- /dev/null +++ b/go/build-a-matrix-with-conditions.go @@ -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 +}