221. Maximal Square

Maximal Square

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

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        if (len(matrix) == 0 or len(matrix[0]) == 0):
            return 0
        m = len(matrix)
        n = len(matrix[0])
        l = 0
        for i in range(m):
            for j in range(n):
                if i == 0 or j == 0:
                    matrix[i][j] = 1 if matrix[i][j]=='1' else 0
                else:
                    matrix[i][j] = min(matrix[i-1][j], matrix[i][j-1], matrix[i-1][j-1]) + 1 if matrix[i][j]=='1' else 0
                l = max(l, matrix[i][j])
        return l * l
posted @ 2020-09-08 21:39  0-1-world  阅读(87)  评论(0编辑  收藏  举报