動機

設計dp時,要注意到return的東西要可以被接

Problem

Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.

 

Example 1:

Input: matrix = [[1,0,1,0,0],[1,0,1,1,1],[1,1,1,1,1],[1,0,0,1,0]]Output: 4

Example 2:

Input: matrix = [[0,1],[1,0]]Output: 1

Example 3:

Input: matrix = [[0]]Output: 0

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 300
  • matrix[i][j] is '0' or '1'.

Sol

設計dp時,要注意到return的東西要可以被接

像這裡就不要回傳面積,回傳邊長可以算出面積,面積同時也不好組合 所以這裡dp是回傳該點在右下角時的最大正方形邊長

class Solution:
    def maximalSquare(self, ms: List[List[str]]) -> int:
        @cache
        def dp(i,j):
            if i < 0 or i >= len(ms) or j < 0 or j >= len(ms[0]) or ms[i][j] == "0":
                return 0
            elif any([dp(i-1,j) == 0, dp(i,j-1) == 0, dp(i-1,j-1) == 0]):
                return 1
            else:
                left, up, dia = dp(i-1,j), dp(i,j-1), dp(i-1,j-1)
                return min(left,up,dia)+1
        return max([max([dp(i,j) for j in range(len(ms[0]))]) for i in range(len(ms))])**2