给定一个二维数组matrix,其中的值不是0就是1,返回全部由1组成的最大子矩形,内部有多少个1.
数组压缩
import java.util.Stack;
public class MaximalRectangle {
public static void main(String[] args) {
char[][] map = {
{'1','1','1','1','1','1'},
{'1','1','1','0','1','1'},
{'1','1','1','1','1','1'},
{'1','0','1','1','1','1'},
{'1','1','1','1','1','1'},
{'1','1','1','1','0','1'},
{'1','1','1','1','1','1'},
};
System.out.println(maximalRect(map));
}
public static int maximalRect(char[][] map){
if(map == null || map.length == 0 || map[0].length == 0){
return 0;
}
int maxArea = 0;
int[] height = new int[map[0].length];
for (int i = 0; i < map.length; i++) { // 行数
for (int j = 0; j < map[0].length; j++) { // 列数
// 数组压缩
height[j] = map[i][j] == '0' ? 0 : height[j]+1;
}
maxArea = Math.max(maxRectFromBottom(height),maxArea);
}
return maxArea;
}
// height是正方图数组, 使用单调栈求出直方图最大长方形面积
public static int maxRectFromBottom(int[] height){
if(height == null || height.length == 0){
return 0;
}
// 3,4,5,6
int maxArea = 0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < height.length; i++) {
while(!stack.isEmpty() && height[stack.peek()] >= height[i]){
int popIndex = stack.pop();
int leftIndex = stack.isEmpty() ? -1 : stack.peek();
int curArea = (i - 1 - leftIndex) * height[popIndex];
maxArea = Math.max(maxArea, curArea);
}
stack.push(i);
}
while(!stack.isEmpty()){
int popIndex = stack.pop();
int leftIndex = stack.isEmpty() ? -1 : stack.peek();
int curArea = (height.length - 1 - leftIndex) * height[popIndex];
maxArea = Math.max(maxArea, curArea);
}
return maxArea;
}
}