// 1 solution 动态规划 classSolution { public: intnumSubmat(vector<vector<int>>& mat){ int m = mat.size(); int n = mat[0].size(); int res = 0;
for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (mat[i][j]) mat[i][j] += j == 0 ? 0 :mat[i][j - 1]; } }
for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (mat[i][j] > 0) { res += mat[i][j]; auto small = mat[i][j]; for (int k = i - 1; k >= 0 && mat[k][j] > 0; --k) { small = min(mat[k][j], small); res += small; } } } }
// 2 solution 单调栈 classSolution { public: intnumSubmat(vector<vector<int>>& mat){ int m = mat.size(); int n = mat[0].size(); int res = 0; vector<int> heights(m + 1, 0);
auto addMutiRow = [&m, &res](vector<int>& heights) { int count = 0; // (row, high) stack<pair<int, int>> st; st.push(make_pair(0, 0)); int i = 1; int sum = 0; int high = 1; while (i < m + 1) { auto top = st.top(); if (heights[i] >= heights[top.first]) { sum += heights[i]; count += sum; st.push(make_pair(i++, high)); high = 1; } else { st.pop(); high += top.second; sum -= ((heights[top.first] - heights[i]) * top.second); } }
return count; };
for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (mat[i][j]) mat[i][j] += j == 0 ? 0 :mat[i][j - 1]; } }
for (int j = 0; j < n; ++j) { for (int i = 0; i < m; ++i) heights[i + 1] = mat[i][j];