Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit a17586a

Browse files
aQuaaQua
aQua
authored and
aQua
committed
221 wrong answer
1 parent be4a27b commit a17586a

File tree

2 files changed

+46
-69
lines changed

2 files changed

+46
-69
lines changed
Lines changed: 39 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,61 @@
11
package Problem0221
22

33
func maximalSquare(matrix [][]byte) int {
4-
max := 0
54
m := len(matrix)
65
if m == 0 {
7-
return max
6+
return 0
87
}
98
n := len(matrix[0])
109
if n == 0 {
11-
return max
10+
return 0
1211
}
1312

14-
checked := make([][]bool, m)
15-
for i := range checked {
16-
checked[i] = make([]bool, n)
17-
}
18-
19-
x := make([]int, 0, m*n*2)
20-
y := make([]int, 0, m*n*2)
21-
22-
push := func(i, j int) {
23-
x = append(x, i)
24-
y = append(y, j)
25-
}
26-
27-
pop := func() (i, j int) {
28-
i = x[0]
29-
x = x[1:]
30-
j = y[0]
31-
y = y[1:]
32-
return
33-
}
34-
35-
isEmpty := func() bool {
36-
return len(x) == 0
37-
}
38-
39-
clean := func() {
40-
x = x[len(x):]
41-
y = y[len(y):]
13+
// dp[i][j] == 以 (i,j) 点为右下角点的符合题意的最大正方形的边长
14+
dp := make([][]int, m)
15+
for i := range dp {
16+
dp[i] = make([]int, n)
17+
if matrix[i][0] == '1' {
18+
dp[i][0] = 1
19+
}
4220
}
43-
44-
size := func() int {
45-
return len(x)
21+
for j := 0; j < n; j++ {
22+
if matrix[0][j] == '1' {
23+
dp[0][j] = 1
24+
}
4625
}
4726

48-
bfs := func(a, b int) {
49-
temp := 0
50-
push(a, b)
51-
var i, j, k int
52-
for !isEmpty() {
53-
k = size()
54-
for k > 0 {
55-
i, j = pop()
56-
k--
57-
if matrix[i][j] == '0' {
58-
clean()
59-
return
60-
}
27+
maxEdge := 0
6128

62-
if i-a <= j-b {
63-
push(i, j+1)
64-
}
65-
if i-a == j-b {
66-
push(i+1, j+1)
67-
}
68-
if i-a >= j-b {
69-
push(i+1, j)
70-
}
71-
}
72-
temp++
73-
if max < temp {
74-
max = temp
75-
}
29+
for i := 1; i < m; i++ {
30+
for j := 1; j < n; j++ {
31+
if matrix[i][j] == '1' {
32+
dp[i][j] = 1 +
33+
min(
34+
dp[i-1][j-1],
35+
min(
36+
dp[i-1][j],
37+
dp[i][j-1],
38+
),
39+
)
7640

77-
if a+temp >= m || b+temp >= n {
78-
clean()
79-
return
41+
maxEdge = max(maxEdge, dp[i][j])
8042
}
8143
}
8244
}
8345

84-
for i := 0; i+max < m; i++ {
85-
for j := 0; j+max < n; j++ {
86-
bfs(i, j)
87-
}
46+
return maxEdge * maxEdge
47+
}
48+
49+
func min(a int, b int) int {
50+
if a < b {
51+
return a
8852
}
53+
return b
54+
}
8955

90-
return max * max
56+
func max(a int, b int) int {
57+
if a > b {
58+
return a
59+
}
60+
return b
9161
}

Algorithms/0221.maximal-square/maximal-square_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,13 @@ var tcs = []struct {
1313
ans int
1414
}{
1515

16+
{
17+
[][]byte{
18+
[]byte("1"),
19+
},
20+
1,
21+
},
22+
1623
{
1724
[][]byte{
1825
[]byte("11111111"),

0 commit comments

Comments
 (0)