LeetCode1277. 统计全为 1 的正方形子矩阵 [Medium]

1277. Count Square Submatrices with All Ones

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

Example 1:

Input: matrix =
[
  [0,1,1,1],
  [1,1,1,1],
  [0,1,1,1]
]
Output: 15
Explanation:
There are 10 squares of side 1.
There are 4 squares of side 2.
There is  1 square of side 3.
Total number of squares = 10 + 4 + 1 = 15.

Example 2:

Input: matrix =
[
  [1,0,1],
  [1,1,0],
  [1,1,0]
]
Output: 7
Explanation:
There are 6 squares of side 1.
There is 1 square of side 2.
Total number of squares = 6 + 1 = 7.

Constraints:

  • 1 <= arr.length <= 300
  • 1 <= arr[0].length <= 300
  • 0 <= arr[i][j] <= 1

题目:给你一个 m * n 的矩阵,矩阵中的元素不是 0 就是 1,请你统计并返回其中完全由 1 组成的 正方形 子矩阵的个数。

思路:参考link。对于点matrix[i][j],将该位置作为正方形右下角,则所有可能的组合数由其临近的左侧和上侧和左上侧能够组成的正方形数决定(可映射到边长)。

LeetCode1277. 统计全为 1 的正方形子矩阵 [Medium]_第1张图片

LeetCode1277. 统计全为 1 的正方形子矩阵 [Medium]_第2张图片
图片来源arkaung

工程代码下载

class Solution {
     
public:
    int countSquares(vector<vector<int>>& matrix) {
     
        int r = matrix.size();
        int c = matrix[0].size();

        int res = 0;
        for(int i = 0; i < r; ++i){
     
            for(int j = 0; j < c; ++j){
     
                if(matrix[i][j] == 1){
     
                    if(i == 0 || j == 0)
                        res += 1;
                    else{
     
                        int cur = min(matrix[i-1][j-1], min(matrix[i][j-1], matrix[i-1][j])) + matrix[i][j];
                        res += cur;
                        matrix[i][j] = cur;
                    }
                }

            }
        }
        return res;
    }
};

你可能感兴趣的:(leetcode)