【LeetCode每天一题】Maximal Rectangle(最大矩阵面积)
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle 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: 6
思路
这道题刚看到的时候,想着应该使用动态规划来及解决,但是对于动态规划方程没能写出来。最后想了半天也没想出来。最后别人的解决办法确实是用动态来解决的。但是这种解决思路自己估计也想不到。他的解决思路就是设置三个辅助数组,一个height数组是记录行高的,两个数组right(从右到1连续出现的下标)和left(从左到右连续出现的下标)。具体可以见图示部分,时间复杂度尾O(m*n), 空间复杂为O(n)。
图示解决
解决代码
1 class Solution(object):
2 def maximalRectangle(self, matrix):
3 """
4 :type matrix: List[List[str]]
5 :rtype: int
6 """
7 if not matrix:
8 return 0
9 m, n = len(matrix), len(matrix[0])
10 left, right, height, max_A = [0]*n, [n]*n, [0]*n, 0 # 申请辅助数组并初始化
11 for i in range(m): # 从第一行开始遍历
12 cur_left, cur_right = 0, n # 用来记录下标
13 for j in range(n): # 从第一个元素开始遍历
14 if matrix[i][j] == "1": # 如果矩阵中当前坐标为1时, 我们将height对应的下标加一,left取cur_left和left[i]中取最大的。
15 height[j], left[j] = height[j]+1, max(left[j], cur_left)
16 else:
17 height[j], left[j], cur_left = 0, 0, j+1 # 否则赋值位0
18 for j in range(n-1, -1, -1): # right数组从末尾开始遍历。
19 if matrix[i][j] == "1":
20 right[j] = min(right[j], cur_right)
21 else:
22 right[j], cur_right = n, j
23 for j in range(n):
24 max_A = max(max_A,(right[j]-left[j])*height[j]) # 计算到前行为止最大的面积
25 return max_A