add: 最大正方形
This commit is contained in:
parent
431ac87901
commit
3b8d9b3f40
@ -259,6 +259,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
|
|||||||
|
|
||||||
- LeetCode 983. 最低票价 https://leetcode-cn.com/problems/minimum-cost-for-tickets/
|
- LeetCode 983. 最低票价 https://leetcode-cn.com/problems/minimum-cost-for-tickets/
|
||||||
|
|
||||||
|
- [最大正方形](src/array/maximal-square.js)
|
||||||
|
|
||||||
|
- LeetCode 221. 最大正方形 https://leetcode-cn.com/problems/maximal-square/
|
||||||
|
- LintCode 436. 最大正方形 https://www.lintcode.com/problem/maximal-square/description
|
||||||
|
|
||||||
## 栈
|
## 栈
|
||||||
|
|
||||||
- [最大矩阵](src/stack/maximal-rectangle.js)
|
- [最大矩阵](src/stack/maximal-rectangle.js)
|
||||||
|
25
src/array/maximal-square.js
Normal file
25
src/array/maximal-square.js
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
/**
|
||||||
|
* @param {character[][]} matrix
|
||||||
|
* @return {number}
|
||||||
|
*/
|
||||||
|
export const maximalSquare = function (matrix) {
|
||||||
|
if (!matrix || !matrix[0]) return 0
|
||||||
|
|
||||||
|
const rows = matrix.length
|
||||||
|
const cols = matrix[0].length
|
||||||
|
let max = 0
|
||||||
|
|
||||||
|
const dp = new Array(rows).fill().map(_ => new Array(cols).fill(0))
|
||||||
|
|
||||||
|
for (let n = 0; n < rows; n++) {
|
||||||
|
for (let i = 0; i < cols; i++) {
|
||||||
|
if (Number(matrix[n][i]) === 1) {
|
||||||
|
if (n === 0 || i === 0) dp[n][i] = 1
|
||||||
|
else dp[n][i] = Math.min(dp[n - 1][i], dp[n][i - 1], dp[n - 1][i - 1]) + 1 // 找规律
|
||||||
|
max = Math.max(max, dp[n][i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return max * max
|
||||||
|
}
|
15
test/array/maximal-square.test.js
Normal file
15
test/array/maximal-square.test.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { maximalSquare } from '../../src/array/maximal-square'
|
||||||
|
|
||||||
|
test('最大正方形', () => {
|
||||||
|
expect(maximalSquare([
|
||||||
|
[1, 0, 1, 0, 0],
|
||||||
|
[1, 0, 1, 1, 1],
|
||||||
|
[1, 1, 1, 1, 1],
|
||||||
|
[1, 0, 0, 1, 0]
|
||||||
|
])).toBe(4)
|
||||||
|
|
||||||
|
expect(maximalSquare([
|
||||||
|
[0, 0, 0],
|
||||||
|
[1, 1, 1]
|
||||||
|
])).toBe(1)
|
||||||
|
})
|
Loading…
Reference in New Issue
Block a user