forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcount-submatrices-with-all-ones.cpp
More file actions
32 lines (30 loc) · 968 Bytes
/
count-submatrices-with-all-ones.cpp
File metadata and controls
32 lines (30 loc) · 968 Bytes
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
// Time: O(m * n)
// Space: O(n)
class Solution {
public:
int numSubmat(vector<vector<int>>& mat) {
int result = 0;
vector<int> heights(mat[0].size());
for (int i = 0; i < mat.size(); ++i) {
for (int j = 0; j < mat[0].size(); ++j) {
heights[j] = (mat[i][j] == 1) ? heights[j] + 1 : 0;
}
result += count(heights);
}
return result;
}
private:
int count(const vector<int>& heights) {
vector<int> dp(heights.size());
vector<int> stk;
for (int i = 0; i < heights.size(); ++i) {
while (!stk.empty() && heights[stk.back()] >= heights[i]) {
stk.pop_back();
}
dp[i] = !stk.empty() ? dp[stk.back()] + heights[i] * (i - stk.back())
: heights[i] * (i - (-1));
stk.emplace_back(i);
}
return accumulate(cbegin(dp), cend(dp), 0);
}
};