【题目】给定一个整型矩阵map,其中的值只有0和1两种,求其中全是1的所有矩阵区域中,最大的矩形区域为1的数量。
思路:
步骤1:矩阵的行数为N,以每一行做切割,统计以当前行作为底的情况下,每个位置往上的1的数量。使用高度数组height来表示。
例如:map =
1 0 1 1
1 1 1 1
1 1 1 0
1).以第一行做切割后,height={1,0,1,1},height[j]表示目前底上(第一行),j位置往上(包括j位置)有多少连续的1。
2).以第二行做切割后,height={2,1,2,2}, 注意从第一行到第二行,height数组的更新是十分方便的,即height[j] =map[i][j] == 0 ? 0 : height[j] + 1。
3).以第三行做切割后,height={3,2,3,0}。
步骤2:对于每一次切割,都用更新后的height数组来求出每一行为底的情况下,最大的矩形是什么。那么多次切割下,最大的那个矩形就是我们要的。对于height数组,可以理解为一个直方图,步骤2的实质就是在一个大的直方图中求最大矩形的面积,如果我们能求出以每一根柱子扩展出去的最大矩形,那么其中的最大的矩形就是我们想找的,具体步骤见maxRecFromBottom()方法。
public class MaxSubMatrix {
public static int maxRecSize(int[][] 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(maxArea, maxRecFromBottom(height));
}
return maxArea;
}
public static int maxRecFromBottom(int[] height) {
if (height == null || height.length == 0) {
return 0;
}
int maxArea = 0;
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < height.length; i++) {
while (!stack.isEmpty() && height[i] <= stack.peek()) {
int j = stack.pop();
int k = stack.isEmpty() ? -1 : stack.peek();
int curArea = (i - k - 1) * height[j];
maxArea = Math.max(maxArea, curArea);
}
stack.push(i);
}
while (!stack.isEmpty()) {
int j = stack.pop();
int k = stack.isEmpty() ? -1 : stack.peek();
int curArea = (height.length - k - 1) * height[j];
maxArea = Math.max(maxArea, curArea);
}
return maxArea;
}
}