[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.

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

统计全为1的正方形子矩阵。题意跟221题非常类似,给你一个只有0和1的二维矩阵,请你统计其中完全由1组成的正方形子矩阵的个数。思路是动态规划。动态规划的定义是dp[i][j]代表的是由(i, j)为右下角组成的矩形的个数。这个定义跟221题几乎一样,221题的定义是由由(i, j)为右下角组成的最大矩形的边长。为什么这个右下角的坐标也能定义能组成的矩形的个数呢,因为比如给你一个2x2的矩阵,如果都是1的话,右下角的坐标也是1,这样由这个右下角的1能组成的矩形有两个,一个是1x1的,一个是2x2的。这一题的状态转移方程也是在看当前坐标的左边,右边和左上角的dp值,以决定当前坐标的dp值。

时间O(mn)

空间O(1) - 因为是原地修改了矩阵的值

Java实现

 1 class Solution {
 2     public int countSquares(int[][] matrix) {
 3         int res = 0;
 4         for (int i = 0; i < matrix.length; i++) {
 5             for (int j = 0; j < matrix[0].length; j++) {
 6                 if (matrix[i][j] > 0 && i > 0 && j > 0) {
 7                     matrix[i][j] = Math.min(matrix[i - 1][j - 1], Math.min(matrix[i - 1][j], matrix[i][j - 1])) + 1;
 8                 }
 9                 res += matrix[i][j];
10             }
11         }
12         return res;
13     }
14 }

相关题目

221. Maximal Square

LeetCode 题目总结

猜你喜欢

转载自www.cnblogs.com/cnoodle/p/12934762.html