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

Solution in python:

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        if not matrix:
            return 0
        if len(matrix) == 1:
            if "1" in matrix[0]:
                return 1
            else: return 0
        length = len(matrix)
        width = len(matrix[0])
        new_arr = [[0 for i in range(width)] for j in range(length)]
        for i in range(length):
            if matrix[i][0] == '1':
                new_arr[i][0] = 1
        for j in range(width):
            if matrix[0][j] == '1':
                new_arr[0][j] = 1
        for i in range(1, length):
            for j in range(1, width):
                if matrix[i][j] == '1':
                    new_arr[i][j] = min(new_arr[i-1][j-1], new_arr[i-1][j], new_arr[i][j-1])+1

        print(new_arr)
        side = max(max(item) for item in new_arr)
        return side**2

Complexity analysis:

  • Time Complexity: O(N*M)
  • Space Complexity: O(N*M)
最后修改日期: 2020年9月29日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。