求最大子矩阵的大小

【题目】给定一个整型矩阵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;

	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值