当前位置:网站首页>leetcode:1139. 最大的以 1 为边界的正方形
leetcode:1139. 最大的以 1 为边界的正方形
2022-07-05 20:43:00 【OceanStar的学习笔记】
题目来源
题目描述
class Solution {
public:
int largest1BorderedSquare(vector<vector<int>>& grid) {
}
};
举个例子:可以肉眼看出一个满足条件的数组边长为 33 ,同时也是最大边长。
vector<vector<int>> grid ={
{
0, 1, 0, 1, 1},
{
1, 1, 1, 1, 1},
{
1, 1, 0, 1, 1},
{
1, 1, 1, 1, 0},
{
0, 1, 1, 1, 1},
{
1, 1, 1, 0, 1},
{
0, 1, 1, 1, 1},
{
1, 1, 1, 0, 1}
};
std::vector<std::vector<int>> grid = {
{
1, 1, 1},
{
1, 0, 1},
{
1, 1, 1}
};
题目解析
动态规划
class Solution {
public:
// 运用动态规划的思想,建立一个三维数组来存储每个点的左侧和上方连续的1的个数
int largest1BorderedSquare(vector<vector<int>>& grid) {
if(grid.empty()){
return 0;
}
int length = grid.size(); //矩阵的长
int width = grid[0].size(); //矩阵的宽
//用dp[i][j][0]来表示第i行第j列的 左边 连续的1的个数
//用dp[i][j][1]来表示第i行第j列的 上面 连续的1的个数
std::vector<std::vector<std::vector<int>>> dp(
length + 1, std::vector<std::vector<int>>(
width + 1, std::vector<int>(
2, 0
)
)
);
int maxLen = 0;
for (int i = 1; i <= length; ++i) {
for (int j = 1; j <= width; ++j) {
if(grid[i - 1][j - 1] == 1){
//因为上面的代码 i 和 j 都是从1开始,到m,n结束,可以理解为在矩形的左边和上边加了一层0,所以实际的dp[i][j][0]其实是grid[i-1][j-1]左边连续的1的个数(包括自身),这样做其实就是为了方便初始化,避免写太多的if-else,是一种很常见的技巧
dp[i][j][0] += dp[i][j - 1][0] + 1;
dp[i][j][1] += dp[i - 1][j][1] + 1;
//尝试以第i行第j列(当前点)为右下角构成正方形
int len = std::min(dp[i][j][0], dp[i][j][1]); //最大可能长度
while (len > 0){
//判断这个可能的正方形右上角左侧是否有连续len个1 && 左下角的上方是否有连续len个1
if(dp[i - len + 1][j][0] >= len && dp[i][j - len + 1][1] >= len){
break;
}
len--;
}
maxLen = std::max(maxLen, len);
}
}
}
return maxLen * maxLen;
}
};
边栏推荐
猜你喜欢
Duchefa p1001 plant agar Chinese and English instructions
研學旅遊實踐教育的開展助力文旅產業發展
研学旅游实践教育的开展助力文旅产业发展
Duchefa d5124 md5a medium Chinese and English instructions
Abnova丨DNA 标记高质量控制测试方案
培养机器人教育创造力的前沿科技
Abnova maxpab mouse derived polyclonal antibody solution
Abnova丨荧光染料 620-M 链霉亲和素方案
基于AVFoundation实现视频录制的两种方式
小程序页面导航
随机推荐
14、Transformer--VIT TNT BETR
插值查找的简单理解
Classic implementation method of Hongmeng system controlling LED
小程序项目结构
Introduction to dead letter queue (two consumers, one producer)
鸿蒙os第四次学习
Duchefa MS medium contains vitamin instructions
haas506 2.0开发教程 - 阿里云ota - pac 固件升级(仅支持2.2以上版本)
中国管理科学研究院凝聚行业专家,傅强荣获智库专家“十佳青年”称号
Abnova CD81 monoclonal antibody related parameters and Applications
表单文本框的使用(二) 输入过滤(合成事件)
Prosci LAG-3 recombinant protein specification
3.3 project evaluation
Analyze the knowledge transfer and sharing spirit of maker Education
科普|英语不好对NPDP考试有影响吗 ?
清除app data以及获取图标
Duchefa丨P1001植物琼脂中英文说明书
How to renew NPDP? Here comes the operation guide!
Frequent MySQL operations cause table locking problems
Abnova DNA marker high quality control test program