Java Topological Sort - 14ms - 50.7MB
As the best approach in 210. Course Schedule II, we can replace HashMap with ArrayList[].\n\nclass Solution {\n    public int[][] buildMatrix(int k, int[][] row
As the best approach in 210. Course Schedule II, we can replace HashMap with ArrayList[].\n```\nclass Solution {\n    public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {\n        Map<Integer, List<Integer>> mapR = new HashMap<>();\n        Map<Integer, List<Integer>> mapC = new HashMap<>();\n        int[] indR = new int[k];\n        int[] indC = new int[k];\n        List<Integer> oR = new ArrayList<>();\n        List<Integer> oC = new ArrayList<>();\n        for (int i = 0; i < rowConditions.length; i++) {\n            int f = rowConditions[i][0];\n            int s = rowConditions[i][1];\n            mapR.putIfAbsent(f, new ArrayList<>());\n            mapR.get(f).add(s);\n            indR[s - 1]++;\n        }\n        for (int i = 0; i < colConditions.length; i++) {\n            int f = colConditions[i][0];\n            int s = colConditions[i][1];\n            mapC.putIfAbsent(f, new ArrayList<>());\n            mapC.get(f).add(s);\n            indC[s - 1]++;\n        }\n        for (int i = 0; i < indR.length; i++) {\n            if (indR[i] == 0) {\n                oR.add(i + 1);\n            }\n        }\n        for (int i = 0; i < oR.size(); i++) {\n            if (!mapR.containsKey(oR.get(i))) {\n                continue;\n            }\n            for (int num : mapR.get(oR.get(i))) {\n                if (--indR[num - 1] == 0) {\n                    oR.add(num);\n                }\n            }\n        }\n        for (int i = 0; i < indC.length; i++) {\n            if (indC[i] == 0) {\n                oC.add(i + 1);\n            }\n        }\n        for (int i = 0; i < oC.size(); i++) {\n            if (!mapC.containsKey(oC.get(i))) {\n                continue;\n            }\n            for (int num : mapC.get(oC.get(i))) {\n                if (--indC[num - 1] == 0) {\n                    oC.add(num);\n                }\n            }\n        }\n        if (oR.size() != k || oC.size() != k) {\n            return new int[0][0];\n        }\n        int[][] ans = new int[k][k];\n        Map<Integer, Integer> rel = new HashMap<>();\n        for (int i = 0; i < k; i++) {\n            ans[k - 1][i] = oC.get(i);\n            rel.put(oC.get(i), i);\n        }\n        for (int i = 0; i < oR.size() - 1; i++) {\n            int tmp = oR.get(i);\n            int col = rel.get(tmp);\n            ans[i][col] = tmp;\n            ans[k - 1][col] = 0;\n        }\n        return ans;  \n    }\n}\n```
['Topological Sort']