ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode 1504] Count Submatrices With All Ones

2021-02-16 06:32:50  阅读:222  来源: 互联网

标签:Count mat int There submatrices height Ones LeetCode side


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

标签:Count,mat,int,There,submatrices,height,Ones,LeetCode,side
来源: https://www.cnblogs.com/lz87/p/14395061.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有