LeetCode 221: Maximal Square

Problem Description

Explanation

To solve this problem, we can use dynamic programming. We will create a 2D array dp where dp[i][j] will represent the size of the largest square ending at position (i, j). We will iterate over the matrix, updating dp[i][j] based on the values of the neighboring cells. The maximum value in the dp array will give us the side length of the largest square, and its area will be the square of this side length.

Here are the steps:

  1. Initialize a 2D array dp of size m x n where dp[i][j] will store the side length of the largest square ending at position (i, j).
  2. Initialize the first row and first column of dp with values from the input matrix as they are.
  3. For each cell (i, j) in the matrix starting from (1, 1), if the current cell is '1':
    • Update dp[i][j] as min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 because we can extend the square only if all three neighbors are also part of a square.
  4. Finally, return the maximum value in the dp array squared as the area of the largest square.

The time complexity of this solution is O(mn) where m and n are the dimensions of the input matrix. The space complexity is also O(mn) for the dp array.

Solutions

class Solution {
    public int maximalSquare(char[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        int[][] dp = new int[m][n];
        int maxSide = 0;

        for (int i = 0; i < m; i++) {
            dp[i][0] = matrix[i][0] - '0';
            maxSide = Math.max(maxSide, dp[i][0]);
        }

        for (int j = 0; j < n; j++) {
            dp[0][j] = matrix[0][j] - '0';
            maxSide = Math.max(maxSide, dp[0][j]);
        }

        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == '1') {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
                    maxSide = Math.max(maxSide, dp[i][j]);
                }
            }
        }

        return maxSide * maxSide;
    }
}

Loading editor...