标题
input:
matrix = [
[1,0,1,0,0],
[1,0,1,1,1],
[1,1,1,1,1],
[1,0,0,1,0]
]
output:
4
思路
对于从第二行的任意一个点,他的值取决于它上面,左边,做上边的值。
代码
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if len(matrix)==0:
return 0
hight = len(matrix)
width = len(matrix[0])
if hight==0 and width==0:
return 0
dp = [[0 for _ in range(width)]for _ in range(hight)]
if hight<2 and width<2:
return int(matrix[0][0])
if hight<2 and width<3:
return max( int(matrix[0][0]),int(matrix[0][1]))
ans = 0
for i in range(hight):
for j in range(width):
dp[i][j] = int(matrix[i][j])
if dp[i][j] >0 and i>0 and j>0:
dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]) + 1
ans = max(ans,dp[i][j])
return ans*ans