Description

Given a rows * columns matrix mat of ones and zeros, return how many submatrices have all ones.

Example 1:

Input: mat = [[1,0,1],
[1,1,0],
[1,1,0]]
Output: 13
Explanation:
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rectangle of side 2x2.
There is 1 rectangle of side 3x1.
Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.

Example 2:

Input: mat = [[0,1,1,0],
[0,1,1,1],
[1,1,1,0]]
Output: 24
Explanation:
There are 8 rectangles of side 1x1.
There are 5 rectangles of side 1x2.
There are 2 rectangles of side 1x3.
There are 4 rectangles of side 2x1.
There are 2 rectangles of side 2x2.
There are 2 rectangles of side 3x1.
There is 1 rectangle of side 3x2.
Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.

Example 3:

Input: mat = [[1,1,1,1,1,1]]
Output: 21

Example 4:

Input: mat = [[1,0,1],[0,1,0],[1,0,1]]
Output: 5

Constraints:

  1. 1 <= rows <= 150
  2. 1 <= columns <= 150
  3. 0 <= mat[i][j] <= 1

分析

题目的意思是:这道题要求出1组成的小矩形,这道题暴力求解肯定会完蛋,我参考了一下别人的思路,首先rows[i][j]表示第i行以j结尾的连续1的个数。然后再遍历该矩阵,统计以i,j为右下角的矩阵的个数,由于我们能够通过rows数组知道以i,j为结尾的连续1的个数,k从第i行到第0行,一个一个的找符合条件的就行了,其中rows[k][j]和rows[i][j]围成的矩形的个数位min(rows[k][j],rows[i][j]),不清楚的话,自己算一个哈哈哈。

代码

class Solution:
def numSubmat(self, mat: List[List[int]]) -> int:
m=len(mat)
n=len(mat[0])
rows=[[0]*n for i in range(m)]
for i in range(m):
for j in range(n):
if(j==0):
rows[i][j]=mat[i][j]
else:
if(mat[i][j]==0):
rows[i][j]=0
else:
rows[i][j]=rows[i][j-1]+1
res=0
for i in range(m):
for j in range(n):
min_num=rows[i][j]
for k in range(i,-1,-1):
min_num=min(min_num,rows[k][j])
if(min_num==0):
break
res+=min_num
return res

参考文献

​[LeetCode] 统计全 1 子矩形​