leetcode 221. 最大正方形

题解

动态规划,dp[i][j] 表示正方形的边长(其中i, j代表正方形的右下角), 地推公式:dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var area int
func maximalSquare(matrix [][]byte) int {
area = 0
m := len(matrix)
if m == 0 {
return area
}
n := len(matrix[0])
dp := make([][]int, m)
for i := 0; i < m ; i++ {
dp[i] = make([]int, n)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if matrix[i][j] == '1' {
computeSquare(dp, i, j)
}
}
}
return area
}

func computeSquare(dp [][]int, i, j int) {
dp[i][j] = 1
area = max(area, dp[i][j])
if i-1 < 0 {
return
}
if j-1 < 0 {
return
}
dp[i][j] += min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1])
area = max(area, dp[i][j]*dp[i][j])
}

func max(a, b int) int {
if a > b {
return a
}
return b
}

func min(a, b int) int {
if a < b {
return a
}
return b
}