[leetcode] 221. Maximal Square && 85. Maximal Rectangle

【信息科学与工程学】【数据科学】数据科学领域 第六篇 算法设计 07 堆、栈、表、矩阵、集合、队列、数组、字符串、树、图、动态规划、结构体、元组的算法01 当前段必须包含所有字符的最后出现位置。1. 字符串分割成最多片段2. 基因序列功能域划分3. 文本段落划分4. 音频声道分离5. 图像色彩分区6. 社交网络社群划分7. 蛋白质结构域8. 音乐乐章分段9. 代码模块划分10. 章节划分特征:一次扫描,贪心确定边界。 阅读详情

Maximal Square

Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.
Example:

Input:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Output: 4

解法

动态规划,找到每一个位置的可以达到的最大的正方形的边长。

class Solution {
public:
    int maximalSquare(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int> > dp(m, vector<int> (n, 0));
        int res = 0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(i == 0 || j == 0)
                    dp[i][j] = matrix[i][j] == '1' ? 1:0;
                else{
                    if(matrix[i][j] == '1')
                        dp[i][j] = min(dp[i][j-1],min(dp[i-1][j],dp[i-1][j-1])) + 1;
                    else
                        dp[i][j] = 0;
                }
                res = max(res, dp[i][j]);
            }
        }
        return res*res;
    }
};

Maximal Rectangle

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing only 1’s and return its area.
Example:

Input:
[
[“1”,“0”,“1”,“0”,“0”],
[“1”,“0”,“1”,“1”,“1”],
[“1”,“1”,“1”,“1”,“1”],
[“1”,“0”,“0”,“1”,“0”]
]
Output: 6

直方图中最大的面积

可以把这个问题变成求直方图中最大的矩形面积;
对矩阵的每一行加上这行之前的所有行构成一个直方图heights,如果当前值为1,则heights[j]++,否则为0
对每一个直方图进行求最大面积值,最后得到的所有直方图的最大面积就是结果。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> heights(n, 0);
        int res = 0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(matrix[i][j] == '1')
                    heights[j] ++;
                else
                    heights[j]= 0;  
            }
            res = max(res,LargeRecinHisto(heights));
        }
        return res;
    }
    
    int LargeRecinHisto(vector<int> heights){
        stack<int> s;
        heights.push_back(0);
        int max_value = 0;
        for(int i=0;i<heights.size();i++){
            if(s.empty() || heights[i] >= heights[s.top()])
                s.push(i);
            else{
                while(!s.empty() && heights[i] < heights[s.top()]){
                    int cur = s.top(); 
                    s.pop();
                    max_value = max(max_value, heights[cur]*(s.empty() ? i : i-s.top()-1));
                }
                s.push(i);
            }   
        }
        return max_value;
    }
};

一个函数解决

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> heights(n+1, 0);
        int res = 0;
        for(int i=0;i<m;i++){
            stack<int> s;
            for(int j=0;j<n+1;j++){
                if(j<n)
                    heights[j] = matrix[i][j] == '1' ? heights[j]+1:0;
                while(!s.empty() && heights[j] <= heights[s.top()]){
                    int cur = s.top(); 
                    s.pop();
                    res = max(res, heights[cur]*(s.empty() ? j : j-s.top()-1));
                }
                s.push(j);
            }
        }
        return res;
    }
};

解法2

构造一个heights数组和解法1相同,然后再构造一个left和right数组
left数组表示:如果当前值matrix[i][j]==1,left[j]为与其相连都为1的左边界位置,否则为0;
right数组表示:如果当前值matrix[i][j]==1,right[j]为与其相连都为1的右边界位置+1,否则为n;
对于任意一个位置的[i][j],面积表示为(right[j]-left[j])*heights[j]。
举个栗子:

[
[1, 1, 0, 0, 1],
[0, 1, 0, 0, 1],
[0, 0, 1, 1, 1],
[0, 0, 1, 1, 1],
[0, 0, 0, 0, 1]
]

第0行:

h: 1 1 0 0 1
l: 0 0 0 0 4
r: 2 2 5 5 5

第1行:

h: 0 2 0 0 2
l: 0 1 0 0 4
r: 5 2 5 5 5

第2行:

h: 0 0 1 1 3
l: 0 0 2 2 4
r: 5 5 5 5 5

第3行:

h: 0 0 2 2 4
l: 0 0 2 2 4
r: 5 5 5 5 5

第4行:

h: 0 0 0 0 5
l: 0 0 0 0 4
r: 5 5 5 5 5

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<int> heights(n, 0), left(n, 0), right(n, n);
        int res = 0;
        for(int i=0;i<m;i++){
            int cur_left = 0, cur_right = n;
            for(int j=0;j<n;j++){
                if(matrix[i][j] == '1'){
                    heights[j]++;
                    left[j] = max(left[j], cur_left);
                }
                else{
                    heights[j] = 0;
                    left[j] = 0;
                    cur_left = j+1;
                }
            }
            
            for(int j=n-1;j>=0;j--){
                if(matrix[i][j] == '1')
                    right[j] = min(right[j], cur_right);
                else{
                    right[j] = n;
                    cur_right = j;
                }
                res = max(res, (right[j] - left[j]) * heights[j]);
            }
        }
        return res;
    }
};

解法3

先统计每一行的连续1的个数,使用一个数组 h_max, 其中 h_max[i][j] 表示第i行,第j个位置水平方向连续1的个数,若 matrix[i][j] 为0,那对应的 h_max[i][j] 也一定为0;
再次遍历每个位置,首先每个位置的 h_max 值都先用来更新结果 res,因为高度为1也可以看作是矩形,然后我们向上方遍历,上方 (i, j-1) 位置也会有 h_max 值,但是用二者之间的较小值才能构成矩形,用新的矩形面积来更新结果 res,这样一直向上遍历,直到遇到0,或者是越界的时候停止,这样就可以找出所有的矩形了。

class Solution {
public:
    int maximalRectangle(vector<vector<char>>& matrix) {
        if(matrix.empty() || matrix[0].empty())
            return 0;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int> > h_max(m, vector<int> (n,0));
        int res = 0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if (matrix[i][j] == '0') continue;
                if (j > 0) h_max[i][j] = h_max[i][j - 1] + 1;
                else h_max[i][0] = 1;
            }
        }
        for(int i=0;i<m;i++){
            for (int j = 0; j < n; ++j) {
                if (h_max[i][j] == 0) continue;
                int mn = h_max[i][j];
                res = max(res, mn);
                for (int k = i - 1; k >= 0 && h_max[k][j] != 0; --k) {
                    mn = min(mn, h_max[k][j]);
                    res = max(res, mn * (i - k + 1));
                }
            }
        }
        return res;
    }
};

参考

https://www.cnblogs.com/grandyang/p/4322667.html

别再只调颜色阈值了!优化K210色块追踪性能的5个关键参数与实战技巧 本文深入探讨了K210色块追踪性能优化的五大核心策略,包括图像预处理参数精细调控、find_blobs参数进阶配置、运动控制算法升级、硬件时序优化以及可视化调试系统构建。通过实战技巧和参数调整方法,帮助开发者提升K210在色块追踪项目中的识别稳定性和响应速度,适用于云台追踪等应用场景。 阅读详情

相关推荐

合成孔径雷达(SAR)的常见工作模式

随着星载SAR技术研究的深入发展,单一的条带模式已经无法满足当今时代的需求,因此许多新的工作模式相继被提出。这些新模式在分辨率和测绘宽度等方面都有所提高,接下来将简要介绍几种常用的工作模式。

m0_51390495的博客 2314

每周LeetCode算法题(八): 题目: 221. Maximal Square & 85. Maximal Rectangle

每周LeetCode算法题(八)题目1: 221. Maximal Square Given a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area. For example, given the following matri

JacKnights的博客 386

告别CANoe?手把手教你用Python+PCAN搭建汽车诊断脚本(附完整代码)

本文详细介绍了如何利用Python和PCAN硬件搭建高性价比的汽车诊断自动化方案,替代昂贵的CANoe工具。通过开源库python-can和udsoncan实现UDS诊断协议,涵盖硬件选择、环境配置、核心功能实现及性能优化,附完整代码示例,助力开发者快速构建诊断脚本。

weixin_42551227的博客 373

LeetCode(85 & 221):最大矩形 Maximal Rectangle & 最大正方形 Maximal Square(Java)

2019.10.14 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新) github:https://github.com/ChopinXBP/LeetCode-Babel 这道题是之前做过的一道题的拓展题:LeetCode(84):柱状图中最大的矩形 Largest Rectangle in Histogram(Java) 从之前的解法思路出发可以有三种方法: 1.动态规...

NJU_ChopinXBP的博客 384

安装破解IAR EWARM 8.2,提供注册机

IAR Embedded Workbench for ARM(IAR for ARM)是一款微处理器的集成开发环境软件,该集成开发环境中包含了IAR的C/C++编译器、 汇编工具、链接器、库管理器、文本编辑器、工程管理器和C-SPY调试器,支持ARM,AVR,MSP430等芯片。   一、安装 双击运行安装程序,点击Install IAR Embedded Workbench for ARM...

睿思派克 4万+

保姆级教程:在Win10/Win11上搞定AppScan 10.0.0安装与许可证激活(含常见报错解决)

本文提供AppScan 10.0.0在Win10/Win11上的详细安装与许可证激活指南,涵盖环境准备、分步安装、文件替换技巧及常见报错解决方案。通过专业的安全测试工具部署实践,帮助用户高效完成安装并避免常见陷阱,提升Web应用安全扫描效率。

weixin_30800987的博客 425

leetcode 84. Largest Rectangle in Histogram 、85. Maximal Rectangle 、221. Maximal Square

84. Largest Rectangle in Histogram https://www.cnblogs.com/grandyang/p/4322653.html 整体思路是递增不处理,当遇到减少时,计算之前所有大于当前高度的最优解。因为实际上只要遇到比你小的,就不可能以你为高度了。索引之间的差刚好能反应当前栈中高度所覆盖的区域,即宽度。 维护一个递增的栈,每次只用以当前栈的ind...

weixin_30569153的博客 191

在 ABAP 环境中创建 Job Catalog Entry 和 Job Template 的完整实践指南

摘要:本文介绍了SAP BTP ABAP环境中Application Job的云原生解决方案,对比传统后台作业模式。重点阐述了Job Catalog Entry和Job Template两大核心概念,通过库存重估业务场景演示如何实现可调度类、创建Job Catalog Entry及Job Template。文章详细说明了从ABAP类到Job Catalog Entry再到Job Template的完整链路,并分享实际项目中的设计经验和注意事项,帮助开发者将传统后台作业迁移到Application Job框架

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 231

Leetcode 221 & 85

Leetcode 221 & 85Leetcode 221 Maximal SquareDescriptionGiven a 2D binary matrix filled with 0’s and 1’s, find the largest square containing only 1’s and return its area.For example, given the following

Zeongwan的博客 437

Smart PLC高速脉冲输入计米轮模块(编码器测速/计米详细讲解)

线缆行业单绞机PLC控制算法详细解读可以参看下面的文章链接:线缆行业单绞机控制算法(详细图解+代码)_RXXW_Dor的博客-优快云博客在了解单绞机之前需要大家对收放卷以及排线控制有一定的了解,不清楚的可以参看下面几篇博客,这里不再赘述,受水平和能力所限,文中难免出现错误和不足之处,诚恳的欢迎大家批评和指正。PLC张力控制(开环闭环算法分析)_RXXW_Dor的博客-优快云博客_plc闭环控制实例。SMART PLC时间间隔定时器应用(高速脉冲测频/测速)_RXXW_Dor的博客-优快云博客。

RXXW_Dor的博客 2819

自适应滤波-----LMS(Least Mean Square)算法

自适应滤波的意义所在 自适应滤波器解决非平稳的过程,因为实际信号的统计特性可能是非平稳的或者是未知的。 自适应滤波器的特点: 1.没有关于待提取信息的先验统计知识 2.直接利用观测数据依据某种判据在观测过程中不断递归更新 3.最优化 自适应滤波分类: 处理器的结构划分:横向结构、格型结构 重复一次计算自适应需要的数据划分:成批处理法、递归处理法 按调节算法...

heda3的博客 10万+

leetcode 221. Maximal Square & 85. Maximal Rectangle

221. Maximal SquareGiven a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.For example, given the following matrix:1 0 1 0 0 1 0 1 1 1 1 1 1 1

Crystal_Zero的博客 535

从零构建Fama-French多因子模型:量化投资系统开发实战

本文详细介绍了如何从零构建Fama-French多因子模型,并将其应用于量化投资系统的开发。首先,文章概述了Fama-French多因子模型的背景、核心原理和架构,解释了其如何通过引入市场风险、规模、价值、盈利和投资等因子来解释股票收益率的变化。接着,文章详细阐述了构建该模型的具体步骤,包括因子的计算、因子暴露的确定以及模型的估计。通过数学模型和公式,文章对模型进行了理论推导,并举例说明了其应用。此外,文章还提供了项目实战的代码案例,从开发环境搭建到源代码实现,逐步指导读者完成量化投资系统的开发。最后,文章

2501_92132293的博客 1224

[LeetCode]221. Maximal Square & 85. Maximal Rectangle

https://leetcode.com/problems/maximal-square/ https://leetcode.com/problems/maximal-rectangle/ 找到01数组中全为1的面积最大的正方形/长方形,返回最大面积 正方形: 二维DP非常简单 public class Solution { public int maxi

gqk289的专栏 257

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

【LeetCode】85. Maximal Rectangle 解题报告(Python)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/maximal-rectangle/description/ 题目描述: Given a 2D binary matrix filled with 0’s and 1’s, find the larges...

负雪明烛 4808

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

LeetCode 221. Maximal Square

DP问题,有点难想,但是理解以后不难。 记 dp[i][j] 为以 a[i][j] 为右下角的正方形的最大边长。 递推公式写起来不难,dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1 if a[i][j]==1 如下图所示,较小的边+1后形成的正方形一定是包含在其他图形中的,也就是说都是1。 class S...

weixin_34088583的博客 88

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

LeetCode #221 - Maximal Square

题目描述:Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.For example, given the following matrix:1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 0 0 1 0 R...

LawFile的博客 285

LeetCode 85. Maximal Rectangle&221. Maximal Square--动态规划

题目链接 221. Maximal Square Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area. For example, given the following matrix: 1 0 1 0

monkey_rose的博客 442

Leetcode刷题笔记-最大矩形,最大正方形

221.Maximal Square 思路: This problem can be solved by dynamic programming. They key to DP is the state equation. In this problem, we define the state asthe maximal size of the square that can be ...

Sengo的博客 746

[LeetCode] 34. Find First and Last Position of Element in Sorted Array Medium

Find First and Last Position of Element in Sorted Array Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. Your algorithm’s runti...

Peng_maple的博客 328

[LeetCode] 17. Letter Combinations of a Phone Number

Letter Combinations of a Phone Number Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just ...

Peng_maple的博客 325

[leetcode] 139. Word Break

Word Break Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. N...

Peng_maple的博客 280

[leetcode] 97. Interleaving String

Interleaving String Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. Example 1: Input: s1 = “aabcc”, s2 = “dbbca”, s3 = “aadbbcbcac” Output: true Example 2: Input: s1 =...

Peng_maple的博客 278

[LeetCode] 4. Median of Two Sorted Arrays

Median of Two Sorted Arrays There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). ...

Peng_maple的博客 263

[leetcode] 149. Max Points on a Line

Max Points on a Line Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Example 1: Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | | o | ...

Peng_maple的博客 256

[LeetCode] 32. Longest Valid Parentheses

Longest Valid Parentheses Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: “(()” Output: 2 Explan...

Peng_maple的博客 253
上一篇: [LeetCode] 78. Subsets && 90. Subsets II
下一篇: [leetcode] 87. Scramble String
Peng_maple
博客等级 码龄10年 0粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值