Description
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区域能够构成正方形的个数。这道题我一开始想着有什么规律,结果发现这些规律都不太对。后面发现是动态规划题目。如果矩阵的当前位置为0,则以它构建的矩阵是0,即dp[i][j]=0,对于其它非0的位置:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])+1
求左上,同行,同列的最小值的值+1,我猜测表示的是当前位置所能构成的正方形的个数,等于其周围最小值的个数+1,这个规律我也不知道怎么推出来的,感觉好像是这个样子,一个位置如果要构成正方形,确实要看左上,上,左,三个位置。
代码
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
m=len(matrix)
n=len(matrix[0])
dp=[[0]*(n+1) for i in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
if(matrix[i-1][j-1]==0):
dp[i][j]=0
else:
dp[i][j]=min(dp[i][j-1],dp[i-1][j-1],dp[i-1][j])+1
res=0
for i in range(m+1):
for j in range(n+1):
res+=dp[i][j]
return res