-
Notifications
You must be signed in to change notification settings - Fork 0
/
221.go
48 lines (41 loc) · 808 Bytes
/
221.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
package p221
/**
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
**/
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
}
func maximalSquare(matrix [][]byte) int {
if matrix == nil || len(matrix) == 0 || len(matrix[0]) == 0 {
return 0
}
rst := 0
dp, preDp := make([]int, len(matrix[0])+1), make([]int, len(matrix[0])+1)
for _, line := range matrix {
dp, preDp = preDp, dp
for i, b := range line {
if b == '0' {
dp[i+1] = 0
} else {
dp[i+1] = min(dp[i], min(preDp[i], preDp[i+1])) + 1
}
rst = max(rst, dp[i+1]*dp[i+1])
}
}
return rst
}