Topological sorting
Code\n\nclass Solution {\n    public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n        List<Integer> sortedByRow = topological
# Code\n```\nclass Solution {\n    public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n        List<Integer> sortedByRow = topologicalSort(rowConditions, k);\n        List<Integer> sortedByCol = topologicalSort(colConditions, k);\n\n        if (sortedByRow.isEmpty() || sortedByCol.isEmpty()) {\n            return new int[0][0];\n        }\n\n        int[][] cellsIndexed = new int[k + 1][2];\n        for (int row = 0; row < sortedByRow.size(); row++) {\n            int cellAtRow = sortedByRow.get(row);\n            cellsIndexed[cellAtRow][0] = row;\n        }\n        for (int col = 0; col < sortedByCol.size(); col++) {\n            int cellAtCol = sortedByCol.get(col);\n            cellsIndexed[cellAtCol][1] = col;\n        }\n\n        int[][] ans = new int[k][k];\n        for (int cell = 1; cell <= k; cell++) {\n            int[] cellCoordinates = cellsIndexed[cell];\n            ans[cellCoordinates[0]][cellCoordinates[1]] = cell;\n        }\n\n        return ans;\n    }\n\n    private List<Integer> topologicalSort(int[][] conditions, int k) {\n        Map<Integer, List<Integer>> adjacency = new HashMap<>();\n\n        for (int[] condition : conditions) {\n            adjacency.putIfAbsent(condition[0], new ArrayList<>());\n            adjacency.get(condition[0]).add(condition[1]);\n        }\n\n        int[] indegreeLookup = new int[k + 1];\n        for (int[] condition : conditions) {\n            indegreeLookup[condition[1]]++;\n        }\n\n        Queue<Integer> q = new ArrayDeque<>();\n        for (int vertex = 1; vertex <= k; vertex++) {\n            if (indegreeLookup[vertex] == 0) {\n                q.offer(vertex);\n            }\n        }\n\n        List<Integer> ans = new ArrayList<>();\n        while (!q.isEmpty()) {\n            int vertex = q.poll();\n            ans.add(vertex);\n\n            List<Integer> adjacents = adjacency.getOrDefault(vertex, new ArrayList<>());\n            for (int adjacentVertex : adjacents) {\n                indegreeLookup[adjacentVertex]--;\n                if (indegreeLookup[adjacentVertex] == 0) {\n                    q.offer(adjacentVertex);\n                }\n            }\n        }\n        \n        return ans.size() < k ? new ArrayList<>() : ans;\n    }\n}\n```
['Java']