LeetCode-221. 最大正方形
在一个由 ‘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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximal-square
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码1:
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
m, n = len(matrix), len(matrix[0])
dp = [[0]*(n+1) for _ in range(m+1)]
maxside = 0
for i in range(m):
for j in range(n):
if matrix[i][j] == '1':
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
maxside = max(dp[i][j], maxside)
return maxside**2
代码2:优化空间
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
m, n = len(matrix), len(matrix[0])
dp = [0]*(n+1)
maxside = 0
for i in range(m):
northwest = 0
for j in range(n):
nextnorthwest = dp[j+1]
if matrix[i][j] == '1':
dp[j+1] = min(dp[j], dp[j+1], northwest) + 1
maxside = max(dp[j+1], maxside)
else:
dp[j+1] = 0
northwest = nextnorthwest
return maxside**2