LeetCode 1277. Count Square Submatrices with All Ones?

Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.

which is count the number of square submatrix that are all one.
remember, square and all 1s.

so let’s say for each 1, it can belongs to multiple submatrix. so we can;t use dp[i][j] as the number of matrixs that contains the 1 in the right bottom part

using extra space

dp[i][j] means the size of biggest square with A[i][j] as bottom-right corner.
dp[i][j] also means the number of squares with A[i][j] as bottom-right corner.
If A[i][j] == 0, no possible square.
If A[i][j] == 1,
we compare the size of square dp[i-1][j-1], dp[i-1][j] and dp[i][j-1].
min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1 is the maximum size of square that we can find.

class Solution {
    public int countSquares(int[][] A) {
        int res = 0;
        int m = A.length;
        int n = A[0].length;
        int[][] dp = new int[m+1][n+1];
        for (int i = 1; i <= A.length; ++i) {
            for (int j = 1; j <= A[0].length; ++j) {
                if (A[i-1][j-1] == 1) {
                    dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
                }
                res += dp[i][j];
            }
        }
        return res;
    }
}

do it in place on A

class Solution {
    public int countSquares(int[][] A) {
        int res = 0;
        for (int i = 0; i < A.length; ++i) {
            for (int j = 0; j < A[0].length; ++j) {
                if (A[i][j] > 0 && i > 0 && j > 0) {
                    A[i][j] = Math.min(A[i - 1][j - 1], Math.min(A[i - 1][j], A[i][j - 1])) + 1;
                }
                res += A[i][j];
            }
        }
        return res;
    }
}

but either way, don’t really understand the meaning of dp[i][j]

refer: https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/441306/JavaC%2B%2BPython-DP-solution

posted @ 2020-11-25 07:24  EvanMeetTheWorld  阅读(18)  评论(0)    收藏  举报