数据结构-全部由1组成的子矩形数量

给定一个二维数组matrix, 其中的值不是0就是1, 返回全部由1组成的子矩形数量。

import java.util.Stack;

public class CountSubmatricesWithAllOnes {
    public static void main(String[] args) {
        int[][] mat = {
                {1,1,1,1,1,1},
                {1,1,1,1,1,1},
                {1,1,1,1,1,1}
        };

        System.out.println(numSubmat(mat));
    }

    public static int numSubmat(int[][] mat){
        if(mat == null || mat.length == 0 || mat[0].length == 0){
            return 0;
        }

        int nums = 0;
        int[] height = new int[mat[0].length];
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                height[j] = mat[i][j] == 0 ? 0 : (height[j] + 1);
            }
            nums += countFromBottom(height);
        }

        return nums;
    }

    public static int countFromBottom(int[] height){
        if(height == null || height.length == 0){
            return 0;
        }

        int nums = 0;
        Stack<Integer> stack = new Stack<Integer>();
        for (int i = 0; i < height.length; i++) {
            if(!stack.isEmpty() && height[stack.peek()] >= height[i]){
                if(height[stack.peek()] == height[i]){
                    stack.pop(); // 如果相等,就弹出栈,不计算当天弹出的索引
                    stack.push(i);
                    continue;
                }

                int popIndex = stack.pop();
                int h = height[popIndex];
                int leftIndex = stack.isEmpty() ? -1 : stack.peek();
                int lenght = i - leftIndex - 1; // 长度
                int leftHight = leftIndex == - 1 ? 0 : height[leftIndex];
                int rightHight = height[i];
                nums = nums + ( lenght * (lenght + 1) / 2 *  (h - Math.max(leftHight,rightHight)) );
            }

            stack.push(i);
        }

        while(!stack.isEmpty()){
            int popIndex = stack.pop();
            int h = height[popIndex];
            int leftIndex = stack.isEmpty() ? -1 : stack.peek();
            int lenght = height.length - leftIndex - 1; // 长度
            int leftHight = leftIndex == - 1 ? 0 : height[leftIndex];
            int rightHight = 0;
            nums = nums + ( lenght * (lenght + 1) / 2 *  (h - Math.max(leftHight,rightHight)) );
        }

        return nums;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值