Leetcode 221. Maximal Square Python3

题目描述:

Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

Example:

Input: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

Output: 4

动态规划方法:

我们用 0 初始化另一个矩阵 dp,维数和原始矩阵维数相同;
dp(i,j) 表示的是由 1 组成的最大正方形的边长;
从 (0,0)开始,对原始矩阵中的每一个 1,我们将当前元素的值更新为
dp(i, j)=min(dp(i−1, j), dp(i−1, j−1), dp(i, j−1))+1

我们还用一个变量记录当前出现的最大边长,这样遍历一次,找到最大的正方形边长 maxlen,那么结果就是 maxlen^2。

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        rows=len(matrix)
        if len(matrix)==0:
            cols=0
        else:
            cols=len(matrix[0])
        dp=[[0]*(cols+1) for i in range(rows+1)]
        maxlen=0

        for i in range(1,rows+1):
            for j in range(1,cols+1):
                if matrix[i-1][j-1]=='1':
                    dp[i][j]=min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1
                    maxlen=max(maxlen,dp[i][j])

        return maxlen*maxlen

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值