当前位置:网站首页>LeetCode:221. 最大正方形
LeetCode:221. 最大正方形
2022-07-06 08:44:00 【Bertil】
在一个由 ‘0’ 和 ‘1’ 组成的二维矩阵内,找到只包含 ‘1’ 的最大正方形,并返回其面积。
示例 1:
输入:matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
输出:4
示例 2:
输入:matrix = [["0","1"],["1","0"]]
输出:1
示例 3:
输入:matrix = [["0"]]
输出:0
提示:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 300
- matrix[i][j] 为 ‘0’ 或 ‘1’
解题思路
1.首先定义一个数组dp表示以[i][j]为正方形右下角的最大边长,定义一个变量max_len表示最大正方形的边长
2.状态转移方程:dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;(取三者的最小值是因为要构成正方形)
3.注意:若左边和上边的点为’1’,则dp[i][j] = 1
代码
/** * @param {character[][]} matrix * @return {number} */
var maximalSquare = function(matrix) {
let max_len = 0;
let dp = Array.from(Array(matrix.length), () => Array(matrix[0].length).fill(0));
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] === '1') {
if (i === 0 || j === 0) {
dp[i][j] = 1;
}else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;
}
max_len = Math.max(max_len, dp[i][j]);
}
}
}
return max_len ** 2;
};
边栏推荐
- C language double pointer -- classic question type
- Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
- 游戏解包的危害及资源加密的重要性
- 超高效!Swagger-Yapi的秘密
- 优秀的软件测试人员,都具备这些能力
- 移位运算符
- egg. JS directory structure
- [MySQL] log
- JVM performance tuning and practical basic theory - Part 1
- Marathon envs project environment configuration (strengthen learning and imitate reference actions)
猜你喜欢
704 二分查找
游戏解包的危害及资源加密的重要性
Target detection - pytorch uses mobilenet series (V1, V2, V3) to build yolov4 target detection platform
Fairguard game reinforcement: under the upsurge of game going to sea, game security is facing new challenges
[brush questions] top101 must be brushed in the interview of niuke.com
swagger设置字段required必填
深度剖析C语言数据在内存中的存储
堆排序详解
pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof
marathon-envs项目环境配置(强化学习模仿参考动作)
随机推荐
软件卸载时遇到trying to use is on a network resource that is unavailable
查看局域网中电脑设备
Synchronized solves problems caused by sharing
个人电脑好用必备软件(使用过)
有效提高软件产品质量,就找第三方软件测评机构
[MySQL] lock
Colorlog combined with logging to print colored logs
移位运算符
Visual implementation and inspection of visdom
hutool优雅解析URL链接并获取参数
Excellent software testers have these abilities
C語言雙指針——經典題型
Delay initialization and sealing classes
Generator parameters incoming parameters
【MySQL】鎖
logback1.3. X configuration details and Practice
What is the role of automated testing frameworks? Shanghai professional third-party software testing company Amway
Process of obtaining the electronic version of academic qualifications of xuexin.com
[embedded] print log using JLINK RTT
2022.02.13 - NC004. Print number of loops