1. 程式人生 > >【LeetCode】221. Maximal Square 解題報告(Python)

【LeetCode】221. Maximal Square 解題報告(Python)

題目描述:

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。設這個DP[i][j]陣列為以i, j位置為右下角頂點的能夠成的最大正方形的邊長。陣列如果是第一行或者第一列,顯然dp和matrix相等。如果是其他位置,當matrix[i][j] = 1時,能夠成的正方形等於左邊、上邊、左上能夠成的正方形邊長的最小值+1.為什麼是最小值?因為只要存在一個0,那麼就沒法構成更大的正方形,這個是很保守的策略。

遞推公式如下:

  1. dp[0][j] = matrix[0][j] (topmost row);
  2. dp[i][0] = matrix[i][0] (leftmost column);
  3. For i > 0 and j > 0: if matrix[i][j] = 0, dp[i][j] = 0; if matrix[i][j] = 1, dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1.

此處輸入圖片的描述

時間複雜度是O(N2),空間複雜度是O(N2)。

class Solution(object):
    def maximalSquare(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """
        if not matrix: return 0
        M = len(matrix)
        N = len(matrix[0])
        dp = [[0] * N for _ in range(M)]
        for
i in range(M): dp[i][0] = int(matrix[i][0]) for j in range(N): dp[0][j] = int(matrix[0][j]) for i in range(1, M): for j in range(1, N): if int(matrix[i][j]) == 1: dp[i][j] = min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1 return max(map(max, dp)) ** 2

參考資料:

日期

2018 年 10 月 10 日 —— 凍成狗