问题:
给定一个仅包含 0 和 1 、大小为 rows x cols 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:6
解释:最大矩形如上图所示。
示例 2:
输入:matrix = []
输出:0
示例 3:
输入:matrix = [["0"]]
输出:0
示例 4:
输入:matrix = [["1"]]
输出:1
示例 5:
输入:matrix = [["0","0"]]
输出:0
提示:
rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 '0' 或 '1'
以下程序实现了这一功能,请你填补空白处内容:
class Solution(object):
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if matrix is None or len(matrix) == 0:
return 0
ls_row, ls_col = len(matrix), len(matrix[0])
left, right, height = [0] * ls_col, [ls_col] * ls_col, [0] * ls_col
maxA = 0
for i in range(ls_row):
curr_left, curr_right = 0, ls_col
for j in range(ls_col):
if matrix[i][j] == '1':
height[j] += 1
else:
height[j] = 0
for j in range(ls_col):
if matrix[i][j] == '1':
left[j] = max(left[j], curr_left)
else:
left[j], curr_left = 0, j + 1
_______________________;
for j in range(ls_col):
maxA = max(maxA, (right[j] - left[j]) * height[j])
return maxA
# %%
s = Solution()
matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
print(s.maximalRectangle(matrix))
解答思路:
空白处应该填入以下内容:
```java
for j in range(ls_col - 1, -1, -1) {
if (matrix[i][j] == '1') {
right[j] = min(right[j], curr_right);
} else {
right[j], curr_right = ls_col, j + 1;
}
}
```
这段代码是在每一行中从右往左遍历矩阵的列。对于每一列,如果当前元素为`1`,则更新该列的右边界为当前右边界和当前列索引中的较小值。如果当前元素为`0`,则将该列的右边界设置为矩阵的列数,并更新当前右边界为下一列的索引减`1`。这样可以确保在计算每个矩形的面积时,使用正确的右边界。
(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)