Advertisement
nikunjsoni

1504

Jun 13th, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int numSubmat(vector<vector<int>>& mat) {
  4.         int rows=mat.size(), cols=mat[0].size();
  5.         vector<int> h(cols+1);
  6.        
  7.         int ans = 0;
  8.         // Have the histogram heights.
  9.         for(int i=0; i<rows; i++){
  10.             for(int j=0; j<cols; j++)
  11.                 h[j] = (mat[i][j]) ? h[j]+1 : 0;
  12.            
  13.             // Get all rectangles that reside on current row.
  14.             ans += countSubmatrices(h);
  15.         }
  16.         return ans;
  17.     }
  18.    
  19.     int countSubmatrices(vector<int> &h){
  20.         int n=h.size(), ans=0;
  21.         stack<int> stk;
  22.         vector<int> sum(n, 0);
  23.         for(int i=0; i<n; i++){
  24.             while(!stk.empty() && h[stk.top()] >= h[i])
  25.                 stk.pop();
  26.             if(!stk.empty()){
  27.                 sum[i] = sum[stk.top()]; // Init to first height smaller than current.
  28.                 sum[i] += h[i]*(i-stk.top()); // All rectangle possible with heights greater than current.
  29.             }
  30.             else{
  31.                 sum[i] = h[i]*(i+1); // If stack is empty, consider all heights.
  32.             }
  33.             ans += sum[i];
  34.             stk.push(i);
  35.         }
  36.         return ans;
  37.     }
  38.    
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement