Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

221. 最大正方形 #53

Open
Geekhyt opened this issue Apr 23, 2021 · 0 comments
Open

221. 最大正方形 #53

Geekhyt opened this issue Apr 23, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Apr 23, 2021

原题链接

状态转移方程

定义 dp[i][j]:以坐标 (i,j) 为右下角的最大正方形边长。

  • (i,j) 为 0 时,无法构成正方形,dp[i][j] = 0

  • (i,j) 为 1 时,dp[i][j] = min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1

一个正方形的最大边长决定于它左方、上方、斜上方的位置所能形成的最大正方形的边长,即:三者的最小值 + 自身的长度 1。

最大正方形

如图:紫色部分代表不断向左、上方尝试。

为了避免边界条件判断,可以将 dp 数组的长和宽都增加 1。

const maximalSquare = function(matrix) {
    if (!matrix.length) return 0
    const dp = new Array(matrix.length + 1).fill(0).map(() => new Array(matrix[0].length + 1).fill(0))
    let maxLen = 0
    for (let i = 1; i < dp.length; i++) { 
        for (let j = 1; j < dp[0].length; j++) {
            if (matrix[i - 1][j - 1] === '1') {
                dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1
                maxLen = Math.max(dp[i][j], maxLen)
            }
        }
    }
    return maxLen * maxLen
}
  • 时间复杂度: O(m * n)
  • 空间复杂度: O(m * n)
@Geekhyt Geekhyt changed the title 62. 不同路径 221. 最大正方形 Apr 23, 2021
@Geekhyt Geekhyt added the 中等 label Jun 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant