221. Maximal Square

221. Maximal Squarearrow-up-right

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

My Solutions:

方法1:建立一个int[][] dp 储存正方形,长度和宽度比matrix大一圈。

Time: O(m * n); Space: O(m * n)

public int maximalSquare(char[][] matrix) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return 0;
    }
    int rows = matrix.length, cols = matrix[0].length;
    int[][] dp = new int[rows + 1][cols + 1];
    int max = 0;
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= cols; j++) {
            if (matrix[i - 1][j - 1] == '1'){ // 注意这里,dp比matrix大一圈所以需要-1
                // dp[i][j] is the smallest number + 1 in the closest square, where the current number is at the right bottom
                dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
                max = Math.max(max, dp[i][j]);
            }
        }
    }
    return max * max;
}

方法2:在每一个matrix[i][j],以此点作为左上点,检查周围能否形成更大的square

Time: O(m * n); Space: O(1)

Last updated