给定一个填充了 0 和 1 的二进制矩阵,找到最大的只包含 1 的矩形并返回其面积。
例如,给出以下矩阵:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
返回 6
详见:https://leetcode.com/problems/maximal-rectangle/description/
Java实现:
class Solution {
public int maximalRectangle(char[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return 0;
}
int res = 0;
int m = matrix.length;
int n = matrix[0].length;
int [] heights = new int[n];
for(int i = 0; i<m; i++){
for(int j = 0; j<n; j++){
heights[j] = matrix[i][j] == '0' ? 0 : heights[j]+1;
}
res = Math.max(res, largestRectangleArea(heights));
}
return res;
}
private int largestRectangleArea(int[] heights) {
int res=0;
int n=heights.length;
for(int i=0;i<n;++i){
if(i+1<n&&heights[i]<=heights[i+1]){
continue;
}
int minH=heights[i];
for(int j=i;j>=0;--j){
minH=Math.min(minH,heights[j]);
int area=minH*(i-j+1);
res=Math.max(res,area);
}
}
return res;
}
}
参考:https://www.cnblogs.com/grandyang/p/4322667.html