LeetCode 221. 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:

1
2
3
4
5
6
7
8
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方法(实际是一种).

  1. dp(i,j) represents the side length of the maximum square whose bottom right corner is the cell with index (i,j) in the original matrix.
    dp(i,j)=min(dp(i−1,j),dp(i−1,j−1),dp(i,j−1))+1.
    Time complexity : O(mn)
    Space complexity : O(mn)

  2. In the previous approach for calculating dp of $i^{th}$row we are using only the previous element and the $(i-1)^{th}$row. Therefore, we don’t need 2D dp matrix as 1D dp array will be sufficient for this.
    dp[j]=min(dp[j-1],dp[j],prev), prev = old dp[j-1].
    Time complexity : O(mn)
    Space complexity : O(n)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# # 2d DP: dp(i,j)=min(dp(i−1,j),dp(i−1,j−1),dp(i,j−1))+1.

# class Solution(object):
# def maximalSquare(self, matrix):
# """
# :type matrix: List[List[str]]
# :rtype: int
# """
# if matrix == []:
# return 0
# res = 0
# m, n = len(matrix), len(matrix[0])
# dp = [[0 for _ in range(n+1)] for _ 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':
# dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])+1
# res = max(res, dp[i][j])
# return res*res


# # 1d DP: dp[j]=min(dp[j−1],dp[j],prev), prev = dp[j-1]

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