Leetcode 221 Maximal Square

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.

a[i][j]表示在以matrix[i][j]为右下角的最大正方形边长

转移方程:

如果当前位置为1,则:

a[i][j] = min(a[i-1][j-1],a[i-1][j],a[i][j-1]) + 1

否则为0

这边开了一个比matrix大一圈的a数组,来避免越界以及第一行和列的拷贝操作

class Solution(object):
    def maximalSquare(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        if not matrix: return 0
        m, n, t = len(matrix),len(matrix[0]), 0
        a = [[0 for i in range(n+1)] for i in range(m+1)]
        for i in range(1,m+1):
            for j in range(1,n+1):
                if matrix[i-1][j-1] == '1':
                    a[i][j] = min(a[i-1][j-1],a[i-1][j],a[i][j-1]) + 1
                    t = max(t,a[i][j])
        return t*t

 

posted @ 2016-05-10 16:01  lilixu  阅读(122)  评论(0编辑  收藏  举报