Topological sort
Complexity\n- Time complexity: O(K^2)\n\n- Space complexity: O(K)\n\n# Code\n\nclass Solution\n{\n    /**\n     * @param int[][] $rowConditions\n     * @param i
# Complexity\n- Time complexity: $$O(K^2)$$\n\n- Space complexity: $$O(K)$$\n\n# Code\n```\nclass Solution\n{\n    /**\n     * @param int[][] $rowConditions\n     * @param int[][] $colConditions\n     * @return int[][]\n     */\n    public function buildMatrix(int $k, array $rowConditions, array $colConditions): array\n    {\n        $sortedRow = $this->topologicalSort($k, $rowConditions);\n        $sortedCol = $this->topologicalSort($k, $colConditions);\n\n        if (count($sortedRow) === 0 || count($sortedCol) === 0) {\n            return [];\n        }\n\n        $r = array_fill(0, $k, 0);\n        $result = array_fill(0, $k, $r);\n\n\n        for ($i = 0; $i < $k; $i++) {\n            $isMatched = false;\n            for ($j = 0; $j < $k; $j++) {\n                if ($sortedRow[$i] === $sortedCol[$j]) {\n                    $result[$i][$j] = $sortedCol[$j];\n                    $isMatched = true;\n                }\n            }\n\n            if ($isMatched === false) {\n                return [];\n            }\n        }\n\n        return $result;\n    }\n\n    /**\n     * @param int $k\n     * @param int[][] $conditions\n     * @return int[]\n     */\n    private function topologicalSort(int $k, array $conditions): array\n    {\n        $wights = array_fill(1, $k, 0);\n\n        $indexed = [];\n        foreach ($conditions as $condition) {\n            $indexed[$condition[0]][] = $condition[1];\n            ++$wights[$condition[1]];\n        }\n\n        $sorted = [];\n        do {\n            asort($wights);\n\n            $firstKey = array_key_first($wights);\n            if ($wights[$firstKey] !== 0) {\n                return [];\n            }\n\n            unset($wights[$firstKey]);\n\n            $sorted[] = $firstKey;\n\n            $next = $indexed[$firstKey] ?? [];\n            foreach ($next as $wight) {\n                --$wights[$wight];\n            }\n        } while (count ($wights) > 0);\n\n        return $sorted;\n    }\n}\n```
['PHP']