Skip to content

Commit 3bdd2d7

Browse files
aQuaaQua
aQua
authored and
aQua
committed
59 finish
1 parent 5e836ce commit 3bdd2d7

File tree

3 files changed

+30
-16
lines changed

3 files changed

+30
-16
lines changed

Algorithms/0059.spiral-matrix-ii/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ For example, Given n = 3, You should return the following matrix:
1212
]
1313
```
1414
## 解题思路
15+
依照题意,设置填充边界,沿着边界填写。
1516

1617
见程序注释

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

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,43 @@
11
package Problem0059
22

33
func generateMatrix(n int) [][]int {
4-
total := n * n
5-
num := 1
6-
res := [][]int{}
4+
if n == 0 {
5+
return [][]int{}
6+
}
77

8-
// 准备矩阵
9-
for i := 0; i < n; i++ {
10-
res = append(res, make([]int, n))
8+
res := make([][]int, n)
9+
for i := range res {
10+
res[i] = make([]int, n)
1111
}
1212

13-
// i 代表了从外往里的第 i 个圈
14-
for i := 0; num <= total; i++ {
13+
// 4 条边界
14+
top, bottom, left, right := 0, n-1, 0, n-1
15+
num := 1
16+
for top <= bottom && left <= right {
1517
// →
16-
for col := i; col < n-i; col++ {
17-
res[i][col] = num
18+
for j := left; j <= right; j++ {
19+
res[top][j] = num
1820
num++
1921
}
22+
top++
2023
// ↓
21-
for row := i + 1; row < n-i; row++ {
22-
res[row][n-i-1] = num
24+
for j := top; j <= bottom; j++ {
25+
res[j][right] = num
2326
num++
2427
}
28+
right--
2529
// ←
26-
for col := n - i - 2; col >= i; col-- {
27-
res[n-i-1][col] = num
30+
for j := right; j >= left; j-- {
31+
res[bottom][j] = num
2832
num++
2933
}
34+
bottom--
3035
// ↑
31-
for row := n - i - 2; row >= i+1; row-- {
32-
res[row][i] = num
36+
for j := bottom; j >= top; j-- {
37+
res[j][left] = num
3338
num++
3439
}
40+
left++
3541
}
3642

3743
return res

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ func Test_Problem0059(t *testing.T) {
2727

2828
qs := []question{
2929

30+
question{
31+
para{0},
32+
ans{
33+
[][]int{},
34+
},
35+
},
36+
3037
question{
3138
para{3},
3239
ans{

0 commit comments

Comments
 (0)