其他分享
首页 > 其他分享> > 最大正方形

最大正方形

作者:互联网

问题:在一个由 '0' 和 '1' 组成的二维矩阵内,找到只包含 '1' 的最大正方形,并返回其面积。

 

 

 输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]

输出:4

解法:动态规划

注意事项:dp的递推公式及边界条件

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        if not matrix or len(matrix) < 1:
            return
        m, n = len(matrix), len(matrix[0])
        length = 0
        dp = [[0] * n for _ in range(m)]      # dp[i][j]表示以(i,j)为右下角正方形的边长
        for i in range(m):
            for j in range(n):
                if matrix[i][j] == "1":
                    if i==0 or j==0:
                        dp[i][j] = 1
                    else:
                        dp[i][j] = min(dp[i-1][j], dp[i-1][j-1], dp[i][j-1]) + 1     # 通过最小边长确定不满足条件
                    length = max(dp[i][j], length)
        return length*length

 

标签:最大,range,len,正方形,length,dp,matrix
来源: https://www.cnblogs.com/demo-deng/p/16632560.html