Given a two-dimensional binary matrix containing only 0 and 1 and size rows x cols, find the largest rectangle containing only 1 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: 6
Explanation: Maximum rectangle As shown in FIG.
Example 2:
Input: matrix = []
Output: 0
Example 3:
Input: matrix = [["0"]]
Output: 0
Example 4:
Input: matrix = [["1"]]
Output: 1
Example 5:
Input: matrix = [["0","0"]]
Output: 0
prompt:
rows == matrix.length
cols == matrix[0].length
0 <= row, cols <= 200
matrix[i][j] 为 ‘0’ 或 ‘1’
Source: LeetCode
Link: https://leetcode-cn.com/problems/maximal-rectangle
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if (m == 0) {
return 0;
}
int n = matrix[0].length;
int[][] left = new int[m][n];
//这题就是在柱状图中的最大矩形(上一篇博客)上暴力求结果
//获得高
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1') {
//最后面有个+1!!!!!!!!!!!!!!!!!
left[i][j] = (j == 0 ? 0 : left[i][j - 1]) + 1;
}
}
}
int ret = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '0') {
continue;
}
int width = left[i][j];
int area = width;
for (int k = i - 1; k >= 0; k--) {
width = Math.min(width, left[k][j]);
area = Math.max(area, (i - k + 1) * width);
}
ret = Math.max(ret, area);
}
}
return ret;
}
}