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
}