zoukankan      html  css  js  c++  java
  • [LeetCode 1504] Count Submatrices With All Ones

    Given a rows * columns matrix mat of ones and zeros, return how many submatrices have all ones.

     

    Example 1:

    Input: mat = [[1,0,1],
                  [1,1,0],
                  [1,1,0]]
    Output: 13
    Explanation:
    There are 6 rectangles of side 1x1.
    There are 2 rectangles of side 1x2.
    There are 3 rectangles of side 2x1.
    There is 1 rectangle of side 2x2. 
    There is 1 rectangle of side 3x1.
    Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.
    

    Example 2:

    Input: mat = [[0,1,1,0],
                  [0,1,1,1],
                  [1,1,1,0]]
    Output: 24
    Explanation:
    There are 8 rectangles of side 1x1.
    There are 5 rectangles of side 1x2.
    There are 2 rectangles of side 1x3. 
    There are 4 rectangles of side 2x1.
    There are 2 rectangles of side 2x2. 
    There are 2 rectangles of side 3x1. 
    There is 1 rectangle of side 3x2. 
    Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.
    

    Example 3:

    Input: mat = [[1,1,1,1,1,1]]
    Output: 21
    

    Example 4:

    Input: mat = [[1,0,1],[0,1,0],[1,0,1]]
    Output: 5
    

     

    Constraints:

    • 1 <= rows <= 150
    • 1 <= columns <= 150
    • 0 <= mat[i][j] <= 1

    Solution 1. O(N^3), using 1D height array

    For each cell of 1, count up its submatrices contribution as the bottom right corner of a rectangle. If we also fixed the bottom left corner, i.e, fix the base length of the current rectangle R, the number of submatrices we get out of R is its height. To do this, we can keep a 1D array that stores the previous row's height information. If h[j] is 0, it means that mat[i - 1][j] is 0. Else it means there are h[j] 1s on top of mat[i][j]. Thus we can expand R's base length B and keep a running minimum height. This min height determines the max rectangle height we can have as we move toward left. When the running min becomes 0, we can terminate.

    class Solution {
        public int numSubmat(int[][] mat) {   
            int m = mat.length, n = mat[0].length, ans = 0;
            int[] h = new int[n];
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    if(mat[i][j] == 1) {
                        h[j]++;
                        int minHeight = h[j];
                        for(int k = j; k >= 0 && minHeight > 0; k--) {
                            minHeight = Math.min(h[k], minHeight);
                            ans += minHeight;                        
                        }
                    }
                    else {
                        h[j] = 0;
                    }
                }
            }
            return ans;
        }
    }

    Solution 2. O(N^2), optimized using montonic stack

    The inefficiency of the O(N^3) solution is that it takes O(N^2) time to compute the submatrices count of one row. It already takes O(N) time to maintain and update the height array row by row so the BCR is O(N) time to compute the submatrices count of one row. To achieve this, let's borrow the monotonic stack idea used in the largest histogram problem. The algorithm is as follows.

    1.  For each row, create two stacks, one for storing indices, one for storing the number of submatrices that have the current cell mat[i][j] as the bottom right corner. 

    2. First loop over the entire row and update height array.

    3. For mat[i][j] with height[j], the submatrices count contributed by using mat[i][j] as the bottom right corner has 2 parts: (1) A rectange with height[j], the area of this rectangle is the submatrices count of this rectangle. (2). let's denote height[k] is the rightmost index k such that height[k] < height[j]. Then because all heights in between indices[k + 1, j] are bigger than height[k], it means whatever submatrices that can be formed using mat[i][k] as the bottom right corner can also be extended to using mat[i][j] as the bottom right corner. 

    To simulate the above, we use an increasing stack. For each mat[i][j] with height[j], we first try to find out the left bound of the rectangle of height h[j], by popping all bigger or equal heights out of the stack. Then we update the current contribution of mat[i][j] in 2 parts: the rectangle plus the extended submatrices by mat[i][k]. As a result, we need a second matching stack that stores a cell's submatrices contribution.  Finally we push j and the newly computed contributions by mat[i][j] and add this contribution to the final answer.

    class Solution {
        public int numSubmat(int[][] mat) {   
            int m = mat.length, n = mat[0].length, ans = 0;
            int[] h = new int[n];
            for(int i = 0; i < m; i++) {
                ArrayDeque<Integer> idxQ = new ArrayDeque<>();
                ArrayDeque<Integer> sumQ = new ArrayDeque<>();
                idxQ.addFirst(-1);
                sumQ.addFirst(0);
                for(int j = 0; j < n; j++) {
                    h[j] = (mat[i][j] == 0 ? 0 : h[j] + 1);
                }
                for(int j = 0; j < n; j++) {
                    int sum = 0;
                    while(idxQ.peekFirst() >= 0 && h[idxQ.peekFirst()] >= h[j]) {
                        idxQ.removeFirst();  
                        sumQ.removeFirst();
                    }
                    sum += h[j] * (j - idxQ.peekFirst()) + sumQ.peekFirst();
                    idxQ.addFirst(j);
                    sumQ.addFirst(sum);
                    ans += sum;
                }
            }
            return ans;
        }
    }

    Related Problems

    [LeetCode 1277] Count Square Submatrices with All Ones

  • 相关阅读:
    scala程序启动时,Could not locate executable nullinwinutils.exe in the Hadoop binaries解决方案
    binlog_format的模式有哪几种?各自的特点是?
    解决IDEA控制台junit不能用Scanner输入问题
    【转】什么是乐观锁,什么是悲观锁
    lyt经典版MySQL基础——流程控制结构
    ambari 2.5.0源码编译安装
    linux(centeros)svn的安装
    机器学习
    算法思想整理
    lucene
  • 原文地址:https://www.cnblogs.com/lz87/p/14395061.html
Copyright © 2011-2022 走看看