221. Maximal Square(dp)

ぃ、小莉子 提交于 2020-03-02 21:51:16

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

用dp来记录以i,j为右下角元素时最大的matrix。状态转移方程比较trick
Solution:

class Solution(object):
    def maximalSquare(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        res = 0
        dp = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))]
        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                dp[i][j] = 1 if matrix[i][j]=='1' else 0
                if i>0 and j>0 and matrix[i][j]=='1':
                    dp[i][j] = 1 + min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1]))
                res = max(res,dp[i][j])
        return res*res
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!