给定一个二维数组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;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.