LeetCode1504. Count Submatrices With All Ones

文章目录

一、题目

Given an m x n binary matrix mat, return the number of submatrices that 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.

Constraints:

1 <= m, n <= 150

mat[i][j] is either 0 or 1.

二、题解

cpp 复制代码
class Solution {
public:
    int numSubmat(vector<vector<int>>& mat) {
        int res = 0;
        int m = mat.size(),n = mat[0].size();
        vector<int> heights(n,0);
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                heights[j] = mat[i][j] == 0 ? 0 : heights[j] + 1;
            }
            res += countFromBottom(heights);
        }
        return res;
    }
    int countFromBottom(vector<int>& heights){
        int n = heights.size();
        int res = 0;
        stack<int> st;
        for(int i = 0;i < n;i++){
            while(!st.empty() && heights[i] <= heights[st.top()]){
                int cur = st.top();
                st.pop();
                if(heights[cur] > heights[i]){
                    int left = st.empty() ? -1 : st.top();
                    int len = i - left - 1;
                    int bottom = max(left == -1 ? 0 : heights[left],heights[i]);
                    res += (heights[cur] - bottom) * len * (len + 1) / 2;
                }
            }
            st.push(i);
        }
        while(!st.empty()){
            int cur = st.top();
            st.pop();
            int left = st.empty() ? -1 : st.top();
            int len = n - left - 1;
            int bottom = left == -1 ? 0 : heights[left];
            res += (heights[cur] - bottom) * len * (len + 1) / 2;
        }
        return res;
    }
};
相关推荐
和光同尘@4 分钟前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_024 分钟前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_998 分钟前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
@areok@38 分钟前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
小王C语言1 小时前
【C++进阶】---- map和set的使用
开发语言·c++
max5006001 小时前
实时多模态电力交易决策系统:设计与实现
图像处理·人工智能·深度学习·算法·音视频
其古寺1 小时前
贪心算法与动态规划:数学原理、实现与优化
算法·贪心算法·动态规划
Elnaij1 小时前
从C++开始的编程生活(8)——内部类、匿名对象、对象拷贝时的编译器优化和内存管理
开发语言·c++
我爱996!1 小时前
LinkedList与链表
数据结构·链表
yb0os12 小时前
RPC实战和核心原理学习(一)----基础
java·开发语言·网络·数据结构·学习·计算机·rpc