题目
给你一个 m * n 的矩阵,矩阵中的元素不是 0 就是 1,请你统计并返回其中完全由 1 组成的 正方形 子矩阵的个数。
链接:https://leetcode.com/problems/count-square-submatrices-with-all-ones/
Given a m * n matrix of ones and zeros, return how many square submatrices have all ones.
Example:
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.
思路及代码
DP
- 同Leetcode-221
- square[i][j]:以i,j为右下角顶点的最大正方形边长
- square[i][j] = matrix[i][j]*(min(square[i-1][j-1], square[i-1][j], square[i][j-1]) + 1)
class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
if not matrix:
return 0
ans = 0
m = len(matrix)
n = len(matrix[0])
square = [[0 for i in range(n)] for j in range(m)]
for i in range(m):
for j in range(n):
if not matrix[i][j]:
continue
if i == 0 or j == 0:
square[i][j] = int(matrix[i][j])
else:
square[i][j] = int(matrix[i][j])*(min(square[i-1][j-1], square[i-1][j], square[i][j-1]) + 1)
ans += square[i][j]
return ans
复杂度
T =
O
(
m
n
)
O(mn)
O(mn)
S =
O
(
m
n
)
O(mn)
O(mn)