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;
    }
};
相关推荐
愚润求学5 分钟前
【专题刷题】二分查找(一):深度解刨二分思想和二分模板
开发语言·c++·笔记·leetcode·刷题
tanyongxi668 分钟前
手撕C++STL list:深入理解双向链表的实现
开发语言·c++·链表
岩中竹8 分钟前
力扣热题100题解(c++)—矩阵
数据结构·c++·程序人生·算法·leetcode·矩阵
YuforiaCode8 分钟前
第十五届蓝桥杯 2024 C/C++组 拼正方形
c语言·c++·蓝桥杯
啊阿狸不会拉杆10 分钟前
数据结构-图
java·c语言·数据结构·c++·python·算法·图论
双叶8361 小时前
(51单片机)LCD展示动画(延时函数)(LLCD1602教程)
c语言·数据库·c++·单片机·嵌入式硬件·51单片机
稻草猫.1 小时前
【Java 数据结构】泛型
java·数据结构
愚润求学1 小时前
【数据结构】哈希表
数据结构·c++·笔记·散列表
倔强的石头1062 小时前
【C++指南】位运算知识详解
java·开发语言·c++
SophiaSSSSS2 小时前
无标注文本的行业划分(行业分类)算法 —— 无监督或自监督学习
学习·算法·分类