题解 | #求最大子矩阵的大小#
求最大子矩阵的大小
http://www.nowcoder.com/practice/ed610b2fea854791b7827e3111431056
import java.util.Stack;
import java.util.Scanner;
public class Main {
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(maxRecFromBottom(height), maxArea);
}
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] <= height[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;
}
public static void main(String[] args) {
//int n, m;
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
int m = sc.nextInt();
int[][] map = new int[n][m];
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
map[i][j] = sc.nextInt();
System.out.println(maxRecSize(map));
}
}
}