class Solution:
def countSquares(self, matrix: List[List[int]]) -> int:
res = 0
row = len(matrix)
col = len(matrix[0])
dp = [[0]*col for _ in range(row)]
for i in range(0,row):
for j in range(0,col):
if matrix[i][j]==0:
continue
if i==0 or j==0:
dp[i][j] = matrix[i][j]
else:
dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))+1
res+=dp[i][j]
return res
总结:动态转移方程是dp[i][j]=min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1;遇到0元素就跳转,遇到行或者列不数字不为0的更行dp数组。