Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
For example, given the following matrix:1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0return 6
对于一个矩形,可以用最高可能的高度来唯一标记该矩形。剩下的宽度由该最高高度所表示矩形的最左边界和最右边界得出。
height:
1 0 1 0 0
2 0 2 1 1
3 1 3 2 2
4 0 0 3 0
left:
0 0 2 0 0
0 0 2 2 2
0 0 2 2 2
0 0 0 3 0
right:
1 5 3 5 5
1 5 3 5 5
1 5 3 5 5
1 5 5 4 5
public class Solution {
public int maximalRectangle(char[][] matrix) {
int m = matrix.length;
if(matrix == null || m == 0) return 0;
int n = matrix[0].length;
int maxA = 0;
int[] right = new int[n], left = new int[n], heights = new int[n]; // rectangle with highest height
Arrays.fill(right,n);
for(int i=0; i<m; i++) {
int curleft = 0, curright = n;
for(int j=0; j<n; j++) {
if(matrix[i][j] == '1') heights[j]++;
else heights[j] =0;
}
for(int j=0; j<n; j++) {
if(matrix[i][j] == '1') left[j] = Math.max(curleft, left[j]); // each i has own left[], each will renew
else{ left[j] = 0; curleft = j+1; } // most next positon to zero
}
for(int j=n-1; j>=0;j--) {
if(matrix[i][j] == '1') right[j] = Math.min(curright, right[j]);
else{ right[j] = n; curright = j; } // remain at last zero position
}
for(int j=0; j<n; j++) {
maxA = Math.max(maxA, (right[j] - left[j])*heights[j]);
}
}
return maxA;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。