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


    题目

    给定一个整形数组 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 + "  ");
        }
    }
    
    
  • 相关阅读:
    volumetric rendering ---fog/ light/cloud
    strand based hair rendering
    一个相当复杂的延迟管线
    wenti
    ubunt tmux X Error of failed request
    Python编程练习题
    ubuntu15.04 安装 pylab失败,先记下来,漫漫看
    翻译:打造基于Sublime Text 3的全能python开发环境
    关于web2py外网访问,图形界面不显示等问题的解决办法
    yii2中gii外网访问的配置方法
  • 原文地址:https://www.cnblogs.com/lizhouwei/p/8725883.html
Copyright © 2020-2023  润新知