Skip to content

Commit c70d79d

Browse files
aQuaaQua
aQua
authored and
aQua
committed
54 accepted
1 parent f33b6d9 commit c70d79d

File tree

3 files changed

+92
-7
lines changed

3 files changed

+92
-7
lines changed

Algorithms/0054.spiral-matrix/README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,4 @@ You should return [1,2,3,6,9,8,7,4,5].
1717
```
1818
## 解题思路
1919

20-
2120
见程序注释
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,42 @@
11
package Problem0054
22

33
func spiralOrder(matrix [][]int) []int {
4+
r := len(matrix)
45

6+
if r == 0 {
7+
return []int{}
8+
}
9+
10+
c := len(matrix[0])
11+
12+
if len(matrix) == 1 {
13+
return matrix[0]
14+
}
15+
16+
res := make([]int, 0, r*c)
17+
18+
res = append(res, matrix[0]...)
19+
20+
for i := 1; i < r-1; i++ {
21+
res = append(res, matrix[i][c-1])
22+
}
23+
24+
for j := c - 1; j >= 0; j-- {
25+
res = append(res, matrix[r-1][j])
26+
}
27+
28+
for i := r - 2; i > 0 && c > 1; i-- {
29+
res = append(res, matrix[i][0])
30+
}
31+
32+
if r == 2 || c <= 2 {
33+
return res
34+
}
35+
36+
nextMatrix := make([][]int, 0, r-2)
37+
for i := 1; i < r-1; i++ {
38+
nextMatrix = append(nextMatrix, matrix[i][1:c-1])
39+
}
40+
41+
return append(res, spiralOrder(nextMatrix)...)
542
}

Algorithms/0054.spiral-matrix/spiral-matrix_test.go

Lines changed: 55 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package Problem0054
22

33
import (
4-
"testing"
54
"fmt"
5+
"testing"
66

77
"github.com/stretchr/testify/assert"
88
)
@@ -19,7 +19,7 @@ type para struct {
1919

2020
// ans 是答案
2121
type ans struct {
22-
one []int
22+
one []int
2323
}
2424

2525
func Test_Problem0054(t *testing.T) {
@@ -29,20 +29,69 @@ func Test_Problem0054(t *testing.T) {
2929

3030
question{
3131
para{
32-
,
32+
[][]int{
33+
[]int{7},
34+
[]int{9},
35+
[]int{6},
36+
},
37+
},
38+
ans{
39+
[]int{7, 9, 6},
40+
},
41+
},
42+
43+
question{
44+
para{
45+
[][]int{
46+
[]int{1, 2, 3},
47+
[]int{4, 5, 6},
48+
[]int{7, 8, 9},
49+
},
50+
},
51+
ans{
52+
[]int{1, 2, 3, 6, 9, 8, 7, 4, 5},
53+
},
54+
},
55+
56+
question{
57+
para{
58+
[][]int{
59+
[]int{1, 2, 3},
60+
[]int{4, 5, 6},
61+
},
3362
},
3463
ans{
35-
,
64+
[]int{1, 2, 3, 6, 5, 4},
3665
},
3766
},
38-
67+
68+
question{
69+
para{
70+
[][]int{
71+
[]int{1, 2, 3},
72+
},
73+
},
74+
ans{
75+
[]int{1, 2, 3},
76+
},
77+
},
78+
79+
question{
80+
para{
81+
[][]int{},
82+
},
83+
ans{
84+
[]int{},
85+
},
86+
},
87+
3988
// 如需多个测试,可以复制上方元素。
4089
}
4190

4291
for _, q := range qs {
4392
a, p := q.ans, q.para
4493
fmt.Printf("~~%v~~\n", p)
4594

46-
ast.Equal(a.one, spiralOrder(p ), "输入:%v", p)
95+
ast.Equal(a.one, spiralOrder(p.matrix), "输入:%v", p)
4796
}
4897
}

0 commit comments

Comments
 (0)