LeetCode 221. Maximal Square----动态规划--谷歌面试算法题--Python解法

寻找二维二进制矩阵中仅包含1的最大正方形并返回其面积。题目来源于LeetCode,是谷歌面试的算法问题。Python解决方案时间复杂度为O(nm),空间复杂度为O(mn)。存在更优的O(m)空间复杂度解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目地址:Maximal Square - LeetCode


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

这道题目意思很容易懂,就是找出最大的正方形。

这道题目是我面XX时遇到的算法题。
根据Google | L3 | Seattle | Sep 2019 [No Offer] - LeetCode Discuss这篇文章,他在面谷歌时遇到了这道算法题。

最容易想到的就是暴力的方法,当然时间复杂度太高,肯定不被接受。

然后面试官提示我用动态规划,我就描述了一下我的算法。因为时间不够,面试官要吃饭去了,就没让我仔细解释。

Python解法如下:

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        result = 0
        if matrix == []:
            return result
        height, width = len(matrix), len(matrix[0])
        dp = []
        for i in range(0, height + 1):
            dp.append([0] * (width + 1))
        for i in range(1, height + 1):
            for j in range(1, width + 1):
                if matrix[i-1][j-1]=='1':
                    dp[i][j] = min(dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]) + 1
                    result = max(dp[i][j], result)
        return result ** 2

时间复杂度为O(nm),空间复杂度为O(mn)。

一般来说上面这个解法就可以了,但有空间复杂度为O(m)的更巧妙的解法。

Python解法如下:

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        result = 0
        if matrix == []:
            return result
        height, width = len(matrix), len(matrix[0])
        dp = [0] * (width + 1)
        prev = 0
        for i in range(1, height + 1):
            for j in range(1, width + 1):
                temp = dp[j]
                if matrix[i - 1][j - 1] == '1':
                    dp[j] = min(dp[j - 1], prev, dp[j])+1
                    result = max(result, dp[j])
                else:
                    dp[j] = 0
                prev = temp
        return result ** 2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值