LeetCode 2392: Build a Matrix With Conditions

Problem Description

Explanation:

To solve this problem, we need to build a k x k matrix that satisfies the given row and column conditions. We can do this by iteratively placing the numbers in the matrix based on the conditions provided. We can start by creating an empty k x k matrix and then filling it according to the given conditions. If at any point we encounter a conflict where a condition cannot be satisfied, we return an empty matrix.

  1. Create a k x k matrix filled with zeros.
  2. Iterate through the row conditions and place the numbers in the corresponding rows based on the conditions.
  3. Iterate through the column conditions and place the numbers in the corresponding columns based on the conditions.
  4. If there is a conflict at any step, return an empty matrix.

:

Solutions

class Solution {
    public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) {
        int[][] matrix = new int[k][k];

        for (int[] rowCond : rowConditions) {
            int above = rowCond[0] - 1;
            int below = rowCond[1] - 1;
            if (matrix[above][0] != 0 && matrix[below][0] != 0) {
                return new int[][]{};
            }
            matrix[above][0] = below + 1;
        }

        for (int[] colCond : colConditions) {
            int left = colCond[0] - 1;
            int right = colCond[1] - 1;
            if (matrix[0][left] != 0 && matrix[0][right] != 0) {
                return new int[][]{};
            }
            matrix[0][left] = right + 1;
        }

        for (int i = 0; i < k; i++) {
            for (int j = 0; j < k; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][j] = getMissingNum(k, i, j, matrix);
                }
            }
        }

        return matrix;
    }

    private int getMissingNum(int k, int row, int col, int[][] matrix) {
        for (int num = 1; num <= k; num++) {
            boolean found = false;
            for (int i = 0; i < k; i++) {
                if (matrix[i][col] == num || matrix[row][i] == num) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return num;
            }
        }
        return -1;
    }
}

Loading editor...