Skip to content

Commit 3b228c1

Browse files
committed
feat: finish 54
1 parent b90e9fb commit 3b228c1

File tree

3 files changed

+132
-0
lines changed

3 files changed

+132
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# [54. Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)
2+
3+
## 2019/09/15
4+
5+
### 题目 💗[medium]
6+
7+
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
8+
9+
Example 1:
10+
11+
```bash
12+
Input:
13+
[
14+
[ 1, 2, 3 ],
15+
[ 4, 5, 6 ],
16+
[ 7, 8, 9 ]
17+
]
18+
Output: [1,2,3,6,9,8,7,4,5]
19+
```
20+
21+
Example 2:
22+
23+
```bash
24+
Input:
25+
[
26+
[1, 2, 3, 4],
27+
[5, 6, 7, 8],
28+
[9,10,11,12]
29+
]
30+
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
31+
```

algorithm/54.SpiralMatrix/main.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package spiralOrder
2+
3+
var hasSeen map[int]bool
4+
5+
func spiralOrder(matrix [][]int) []int {
6+
if len(matrix) == 0 {
7+
return []int{}
8+
}
9+
hasSeen = map[int]bool{}
10+
lenx := len(matrix[0])
11+
leny := len(matrix)
12+
res := []int{}
13+
x, y := 0, 0
14+
direct := 0
15+
for i := 0; i < lenx*leny; i++ {
16+
17+
res = append(res, matrix[y][x])
18+
hasSeen[matrix[y][x]] = true
19+
if isBound(matrix, x, y, direct) {
20+
direct++
21+
}
22+
switch direct % 4 {
23+
case 0:
24+
// right 0
25+
x++
26+
case 1:
27+
// down 1
28+
y++
29+
case 2:
30+
// left 2
31+
x--
32+
case 3:
33+
// up 3
34+
y--
35+
}
36+
}
37+
return res
38+
}
39+
40+
func isBound(matrix [][]int, x, y, direct int) bool {
41+
switch direct % 4 {
42+
case 0:
43+
x++
44+
case 1:
45+
y++
46+
case 2:
47+
x--
48+
case 3:
49+
y--
50+
}
51+
if x < 0 ||
52+
y < 0 ||
53+
y > len(matrix)-1 ||
54+
x > len(matrix[0])-1 {
55+
return true
56+
}
57+
if _, ok := hasSeen[matrix[y][x]]; ok {
58+
return true
59+
}
60+
return false
61+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package spiralOrder
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
var tcs = []struct {
10+
N1 [][]int
11+
ans []int
12+
}{
13+
{
14+
[][]int{
15+
[]int{1, 2, 3},
16+
[]int{4, 5, 6},
17+
[]int{7, 8, 9},
18+
},
19+
[]int{1, 2, 3, 6, 9, 8, 7, 4, 5},
20+
},
21+
{
22+
[][]int{
23+
[]int{1, 2, 3, 4},
24+
[]int{5, 6, 7, 8},
25+
[]int{9, 10, 11, 12},
26+
},
27+
[]int{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7},
28+
},
29+
{
30+
[][]int{},
31+
[]int{},
32+
},
33+
}
34+
35+
func Test_bitwiseComplement(t *testing.T) {
36+
ast := assert.New(t)
37+
for _, tc := range tcs {
38+
ast.Equal(tc.ans, spiralOrder(tc.N1), "输入:%v", tc)
39+
}
40+
}

0 commit comments

Comments
 (0)