您的位置:首页 > 其它

Leetcode: Maximal Square

2015-09-12 13:54 176 查看

Question

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

For example, given the following matrix:

1 0 1 0 0

1 0 1 1 1

1 1 1 1 1

1 0 0 1 0

Return 4.

Credits:

Special thanks to @Freezen for adding this problem and creating all test cases.

Hide Tags Dynamic Programming

Hide Similar Problems

Solution

Get idea from here

[code]class Solution(object):
    def maximalSquare(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """

        if matrix==None or len(matrix)==0:
            return 0

        m, n = len(matrix), len(matrix[0])
        dp = [[0]*n for dummy in range(m)]
        res = 0

        for ind in range(m):
            dp[ind][0] = 1 if matrix[ind][0]=='1' else 0
            if dp[ind][0]>res:
                res = dp[ind][0]

        for ind in range(n):
            dp[0][ind] = 1 if matrix[0][ind]=='1' else 0
            if dp[0][ind]>res:
                res = dp[0][ind]

        for mind in range(1,m):
            for nind in range(1,n):
                if matrix[mind][nind]=='1':
                    dp[mind][nind] = min([ dp[mind-1][nind], dp[mind][nind-1], dp[mind-1][nind-1] ]) + 1
                    if dp[mind][nind]>res:
                        res = dp[mind][nind]
                else:
                    dp[mind][nind] = 0

        return res**2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: