您的位置:首页 > 其它

在一个只包含0,1的二维数组中找到最大矩形的面积

2016-03-29 22:46 459 查看
1、用一个height数组表示从从上到下连续的1的高度。left,right表示当前矩形的边界。maxA = max(maxA,(right[j]-left[j])*height[j]);

例如:

0 0 0 1 0 0 0

0 0 1 1 1 0 0

0 1 1 1 1 1 0

对第一行:

l: 0 0 0 3 0 0 0

r: 7 7 7 4 7 7 7

对第二行:

l: 0 0 2 3 2 0 0

r: 7 7 5 4 5 7 7

对第三行:

l: 0 1 2 3 2 1 0

r: 7 6 5 4 5 6 7

int maximalRectangle(int[][] matrix) {
if (matrix.length == 0)return 0;
int m = matrix.length;
int n = matrix[0].length;
int left[] = new int
;
int right[] = new int
;
int height[] = new int
;
Arrays.fill(left, 0);
Arrays.fill(right, n);
Arrays.fill(height, 0);

int maxA = 0;
for (int i = 0; i < m; i++) {
int cur_left = 0, cur_right = n;
for (int j = 0; j < n; j++) { // compute height (can do this from either side)
if (matrix[i][j] == '1')
height[j]++;
else
height[j] = 0;
}
for (int j = 0; j < n; j++) { // compute left (from left to right)
if (matrix[i][j] == '1')
left[j] = Math.max(left[j], cur_left);
else {
left[j] = 0;
cur_left = j + 1;
}
}
// compute right (from right to left)
for (int j = n - 1; j >= 0; j--) {
if (matrix[i][j] == '1')
right[j] = Math.min(right[j], cur_right);
else {
right[j] = n;
cur_right = j;
}
}
// compute the area of rectangle (can do this from either side)
for (int j = 0; j < n; j++)
maxA = Math.max(maxA, (right[j] - left[j]) * height[j]);
}
return maxA;
}


2、先计算出高度,在用stack来计算最大的面积。O(n^2)

int maximalRectangle(int[][] matrix) {
if (matrix.length == 0)return 0;
int m = matrix.length;
int n = matrix[0].length;
int height[] = new int[n+1];
height
=0;

int maxA = 0;
for (int i = 0; i < m; i++) {
//compute height
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1')
height[j]++;
else
height[j] = 0;
}
//compute max area by height with stack
Stack<Integer> s = new Stack<>();
for (int j = 0; j <= n; j++) {
if (s.isEmpty()||height[s.peek()]<=height[j])
s.push(j);
else {
while(!s.isEmpty()&&height[j]<height[s.peek()]){
maxA =Math.max(maxA, height[s.pop()]*(s.isEmpty()?j:(j-s.peek()-1))) ;
}
s.push(j);
}
}
}
return maxA;
}


3、计算出高度后直接暴力计算。O(n^3)

int maximalRectangle(int[][] matrix) {
if (matrix.length == 0)return 0;
int m = matrix.length;
int n = matrix[0].length;
int height[] = new int[n+1];
height
=0;

int maxA = 0;
for (int i = 0; i < m; i++) {
//compute height
for (int j = 0; j < n; j++) {
if (matrix[i][j] == '1')
height[j]++;
else
height[j] = 0;
}
//compute max area by height
maxA=Math.max(maxA,getMaxArea(height));
}
return maxA;
}

public int getMaxArea(int []height){
int maxA=0;
for(int i=0;i<height.length;i++){
int j=i-1;
//compute maxHeight in i...0 end with i
int maxtemp=height[i];
int minHeight=height[i];
while(j>=0){
if(height[j]==0)break;
minHeight=Math.min(minHeight, height[j]);
maxtemp=Math.max(maxtemp, minHeight*(i-j+1));
j--;
}
maxA=Math.max(maxtemp, maxA);
}
return maxA;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  求0-1矩形面积