《程序员代码面试指南》第一章 栈和队列 求最大子矩阵大小

题目

给定一个整形数组 map,其中值只有0和1两种,求所有全是1的所有子矩阵中,最大的矩阵全是1的数量

java代码

/**
 * @Description: 求最大子矩阵大小
 * @Author: lizhouwei
 * @CreateDate: 2018/4/6 0:12
 * @Modify by:
 * @ModifyDate:
 */
public class Chapter1_9 {
    public int maxSubMatrixSize(int[][] map) {
        if (map == null) {
            return 0;
        }
        int[] height = new int[map[0].length];
        int maxSize = 0;
        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;
            }
            maxSize = Math.max(getMatrixMaxSize(height), maxSize);
        }
        return maxSize;
    }

    public int getMatrixMaxSize(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int maxSize = 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();
                //例如: i=6,k =4 则 元素的边界为4到6,
                maxSize = Math.max((i - k - 1) * height[j], maxSize);
            }
            stack.push(i);
        }
        //栈中可能还有未计算完的元素,此时height的长度作为元素的边界
        while (!stack.isEmpty()) {
            int j = stack.pop();
            int k = stack.isEmpty() ? -1 : stack.peek();
            maxSize = Math.max((height.length - k - 1) * height[j], maxSize);
        }
        return maxSize;
    }

    //测试
    public static void main(String[] args) {
        Chapter1_9 chapter = new Chapter1_9();
        int[][] arr = {{1, 0, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 0}};
        int res = chapter.maxSubMatrixSize(arr);
        System.out.print(res + "  ");
    }
}

posted @ 2018-04-06 01:17  lizhouwei  阅读(152)  评论(0编辑  收藏  举报