在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
示例 2:
输入:matrix = [["0","1"],["1","0"]]
输出:1
示例 3:
输入:matrix = [["0"]]
输出:0
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] 为 '0' 或 '1'
dp
dp数组维护的正方形的变长
dp[i+1][j+1]=min(min(dp[i+1][j],dp[i][j+1]),dp[i][j])
那最大正方形的面积就是 最大的边长*最大的边长
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
n,m = len(matrix),len(matrix[0])
dp = [[0 for _ in range (m+1)] for _ in range(n+1)]
side=0
for i in range(n):
for j in range(m):
if matrix[i][j]=="1":
dp[i+1][j+1]=min(min(dp[i+1][j],dp[i][j+1]),dp[i][j])+1
side=max(side,dp[i+1][j+1])
return side*side