Skip to content

Commit 8a9163b

Browse files
committed
59 翻新
1 parent 2f710b5 commit 8a9163b

File tree

3 files changed

+39
-32
lines changed

3 files changed

+39
-32
lines changed
Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
# [59. Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii/)
22

33
## 题目
4-
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
54

6-
```
5+
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
6+
7+
```text
78
For example, Given n = 3, You should return the following matrix:
89
[
910
[ 1, 2, 3 ],
1011
[ 8, 9, 4 ],
1112
[ 7, 6, 5 ]
1213
]
1314
```
15+
1416
## 解题思路
17+
1518
依照题意,设置填充边界,沿着边界填写。
1619

1720
见程序注释

Algorithms/0059.spiral-matrix-ii/spiral-matrix-ii.go

Lines changed: 33 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,43 +2,47 @@ package problem0059
22

33
func generateMatrix(n int) [][]int {
44
if n == 0 {
5-
return [][]int{}
5+
return nil
66
}
77

88
res := make([][]int, n)
99
for i := range res {
1010
res[i] = make([]int, n)
1111
}
1212

13-
// 4 条边界,依照题意,沿着边界填写
14-
top, bottom, left, right := 0, n-1, 0, n-1
15-
num := 1
16-
for top <= bottom && left <= right {
17-
// →
18-
for j := left; j <= right; j++ {
19-
res[top][j] = num
20-
num++
21-
}
22-
top++
23-
// ↓
24-
for j := top; j <= bottom; j++ {
25-
res[j][right] = num
26-
num++
27-
}
28-
right--
29-
// ←
30-
for j := right; j >= left; j-- {
31-
res[bottom][j] = num
32-
num++
33-
}
34-
bottom--
35-
// ↑
36-
for j := bottom; j >= top; j-- {
37-
res[j][left] = num
38-
num++
39-
}
40-
left++
13+
max := n * n
14+
next := nextFunc(n)
15+
16+
for i := 1; i <= max; i++ {
17+
x, y := next()
18+
res[x][y] = i
4119
}
4220

4321
return res
4422
}
23+
24+
func nextFunc(n int) func() (int, int) {
25+
top, down := 0, n-1
26+
left, right := 0, n-1
27+
x, y := 0, -1
28+
dx, dy := 0, 1
29+
return func() (int, int) {
30+
x += dx
31+
y += dy
32+
switch {
33+
case y+dy > right:
34+
top++
35+
dx, dy = 1, 0
36+
case x+dx > down:
37+
right--
38+
dx, dy = 0, -1
39+
case y+dy < left:
40+
down--
41+
dx, dy = -1, 0
42+
case x+dx < top:
43+
left++
44+
dx, dy = 0, 1
45+
}
46+
return x, y
47+
}
48+
}

Algorithms/0059.spiral-matrix-ii/spiral-matrix-ii_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ func Test_Problem0059(t *testing.T) {
3030
question{
3131
para{0},
3232
ans{
33-
[][]int{},
33+
nil,
3434
},
3535
},
3636

0 commit comments

Comments
 (0)