Kotlin Topological Sort | Kahn's Algorithm
\nclass Solution {\n    data class Node (var `val`: Int, val `in`: MutableList<Int>, val `out`: MutableList<Int>)\n    fun buildMatrix(k: Int, rowConditions: Ar
```\nclass Solution {\n    data class Node (var `val`: Int, val `in`: MutableList<Int>, val `out`: MutableList<Int>)\n    fun buildMatrix(k: Int, rowConditions: Array<IntArray>, colConditions: Array<IntArray>): Array<IntArray> {\n        var rowSorted = listOf<Int>()\n        var colSorted = listOf<Int>()\n        for (curr in 0 until 2) {\n            val topoSorted = mutableListOf<Node>()\n            val nodes = Array(k + 1) { Node(it, mutableListOf(), mutableListOf()) }\n            val conditions = if (curr == 0) rowConditions else colConditions\n            \n            for (i in conditions) {\n                nodes[i[0]].out.add(i[1])\n                nodes[i[1]].`in`.add(i[0])\n            }\n            val set = mutableSetOf<Node>()\n            for (i in nodes.indices) {\n                if (nodes[i].`in`.isEmpty()) set.add(nodes[i])\n            }\n            \n            while (set.isNotEmpty()) {\n                val n = set.first()\n                set.remove(n)\n                topoSorted.add(n)\n                val out = n.out.toList()\n                for (node in out) {\n                    val m = nodes[node]\n                    nodes[n.`val`].out.remove(m.`val`)\n                    nodes[m.`val`].`in`.remove(n.`val`)\n                    if (m.`in`.isEmpty()) set.add(m)\n                }\n            }\n            \n            var cycle = false\n            for (i in nodes) {\n                if (i.`in`.isNotEmpty() || i.out.isNotEmpty()) {\n                    cycle = true\n                    break\n                }\n            }\n            if (cycle) return arrayOf()\n            var assign = topoSorted.subList(1, topoSorted.size).map { it.`val` }\n            if (curr == 0) rowSorted = assign\n            else colSorted = assign\n        }\n    \n        val matrix = Array(k) { IntArray(k) { 0 } }\n        val y = HashMap<Int, Int>()\n        val x = HashMap<Int, Int>()\n        for (i in rowSorted.indices) {\n            y[rowSorted[i]] = i\n        }\n        for (i in colSorted.indices) {\n            x[colSorted[i]] = i\n        }\n        for (i in y) {\n            val yVal = i.value\n            val xVal = x[i.key]!!\n            matrix[yVal][xVal] = i.key\n        }\n        return matrix\n    }\n}\n```
['Topological Sort', 'Kotlin']