diff --git a/README.md b/README.md index cf7ff98..d62267f 100644 --- a/README.md +++ b/README.md @@ -259,6 +259,11 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重 - 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) diff --git a/src/array/maximal-square.js b/src/array/maximal-square.js new file mode 100644 index 0000000..233441f --- /dev/null +++ b/src/array/maximal-square.js @@ -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 +} diff --git a/test/array/maximal-square.test.js b/test/array/maximal-square.test.js new file mode 100644 index 0000000..3e31906 --- /dev/null +++ b/test/array/maximal-square.test.js @@ -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) +})