|
| 1 | +package com.fishercoder.solutions.thirdthousand; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.LinkedList; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Queue; |
| 7 | + |
| 8 | +public class _2392 { |
| 9 | + public static class Solution1 { |
| 10 | + /** |
| 11 | + * I figured out I needed to use Kahn's algorithm to topologically sort both rowConditions and colConditions, |
| 12 | + * but unsure how to fill the matrix. |
| 13 | + * https://leetcode.com/problems/build-a-matrix-with-conditions/editorial/ is brilliant as of how to build the matrix: |
| 14 | + * using its slides to step through helps a lot! |
| 15 | + */ |
| 16 | + public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) { |
| 17 | + int[] topologicallySortedRows = topologicalSort(rowConditions, k); |
| 18 | + int[] topologicallySortedCols = topologicalSort(colConditions, k); |
| 19 | + if (topologicallySortedRows.length == 0 || topologicallySortedCols.length == 0) { |
| 20 | + return new int[][]{}; |
| 21 | + } |
| 22 | + int[][] matrix = new int[k][k]; |
| 23 | + for (int i = 0; i < k; i++) { |
| 24 | + for (int j = 0; j < k; j++) { |
| 25 | + if (topologicallySortedRows[i] == topologicallySortedCols[j]) { |
| 26 | + matrix[i][j] = topologicallySortedCols[j]; |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + return matrix; |
| 31 | + } |
| 32 | + |
| 33 | + private int[] topologicalSort(int[][] conditions, int k) { |
| 34 | + List<Integer>[] adj = new ArrayList[k + 1]; |
| 35 | + for (int i = 0; i <= k; i++) { |
| 36 | + adj[i] = new ArrayList<>(); |
| 37 | + } |
| 38 | + int[] indegree = new int[k + 1]; |
| 39 | + int[] order = new int[k]; |
| 40 | + int index = 0; |
| 41 | + for (int[] x : conditions) { |
| 42 | + adj[x[0]].add(x[1]); |
| 43 | + indegree[x[1]]++; |
| 44 | + } |
| 45 | + Queue<Integer> q = new LinkedList<>(); |
| 46 | + for (int i = 1; i <= k; i++) { |
| 47 | + if (indegree[i] == 0) { |
| 48 | + q.offer(i); |
| 49 | + } |
| 50 | + } |
| 51 | + while (!q.isEmpty()) { |
| 52 | + Integer curr = q.poll(); |
| 53 | + order[index++] = curr; |
| 54 | + k--; |
| 55 | + for (int v : adj[curr]) { |
| 56 | + indegree[v]--; |
| 57 | + if (indegree[v] == 0) { |
| 58 | + q.offer(v); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + if (k != 0) { |
| 63 | + return new int[0]; |
| 64 | + } |
| 65 | + return order; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments