221. Maximal Square(dp)

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
posted @ 2019-07-12 20:34  bernieloveslife  阅读(120)  评论(0编辑  收藏  举报