[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 的矩阵,如果矩阵内的 4 个位置都是 1 的话,右下角的坐标也是 1,这样由这个右下角的 1 能组成的矩形有两个,一个是1x1的,一个是2x2的。这一题的状态转移方程也是在看当前坐标的左边,右边和左上角的 dp 值,以决定当前坐标的 dp 值。

时间O(mn)

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

Java实现

 1 class Solution {
 2     public int countSquares(int[][] matrix) {
 3         // corner case
 4         if (matrix == null || matrix.length == 0) {
 5             return 0;
 6         }
 7 
 8         // normal case
 9         int m = matrix.length;
10         int n = matrix[0].length;
11         int res = 0;
12         for (int i = 0; i < m; i++) {
13             for (int j = 0; j < n; j++) {
14                 if (i > 0 && j > 0 && matrix[i][j] > 0) {
15                     matrix[i][j] = min(
16                         matrix[i - 1][j],
17                         matrix[i][j - 1],
18                         matrix[i - 1][j - 1]
19                     ) + 1;
20                 }
21                 res += matrix[i][j];
22             }
23         }
24         return res;
25     }
26 
27     private int min(int a, int b, int c) {
28         return Math.min(a, Math.min(b, c));
29     }
30 }

 

相关题目

221. Maximal Square

1277. Count Square Submatrices with All Ones

LeetCode 题目总结

posted @ 2020-05-22 02:17  CNoodle  阅读(580)  评论(0编辑  收藏  举报