Skip to content

Commit 6a5e30d

Browse files
committed
add LeetCode 221. 最大正方形
1 parent e51ff89 commit 6a5e30d

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Diff for: DP/LeetCode 221. 最大正方形.md

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
6+
7+
示例:
8+
9+
```javascript
10+
输入:
11+
12+
1 0 1 0 0
13+
1 0 1 1 1
14+
1 1 1 1 1
15+
1 0 0 1 0
16+
17+
输出: 4
18+
```
19+
20+
来源:力扣(LeetCode)
21+
链接:https://leetcode-cn.com/problems/maximal-square
22+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
23+
24+
25+
## 解题思路
26+
要想求得最大正方形,通过找规律,我们不难发现,对于(i > 0 && j > 0)情况,当前位置边长长度等于左,左上,上三个方向边长长度的最小值,然后加1,于是我们遍历整个矩阵,对于当前值为1的情况,我们每次求一下它能拓展到的最大边长,然后每次迭代求出结果的最大边长,那么面积就是边长*边长返回即可。
27+
28+
29+
```javascript
30+
/**
31+
* @param {character[][]} matrix
32+
* @return {number}
33+
*/
34+
var maximalSquare = function (matrix) {
35+
if (!matrix || !matrix.length) return 0;
36+
let res = 0; // 设置最长边长变量
37+
let n = matrix.length, m = matrix[0].length;
38+
for (let i = 0; i < n; i++) {
39+
for (let j = 0; j < m; j++) {
40+
if (matrix[i][j] == 1) {
41+
// 对于(i > 0 && j > 0)情况,当前位置边长长度等于左,左上,上三个方向边长长度的最小值,然后加1
42+
(i > 0 && j > 0) && (matrix[i][j] = Math.min(matrix[i - 1][j], matrix[i - 1][j - 1], matrix[i][j - 1]) + 1);
43+
}
44+
res = Math.max(res, matrix[i][j]); // 迭代求最长边长
45+
}
46+
}
47+
return res ** 2; // 返回边长*边长
48+
};
49+
```
50+
51+
## 最后
52+
文章产出不易,还望各位小伙伴们支持一波!
53+
54+
往期精选:
55+
56+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
57+
58+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
59+
60+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
61+
62+
63+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
64+
65+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
66+
67+
```javascript
68+
学如逆水行舟,不进则退
69+
```
70+
71+

0 commit comments

Comments
 (0)