Skip to content

Commit 2b12b97

Browse files
committed
54. Spiral Matrix
1 parent 1900374 commit 2b12b97

File tree

3 files changed

+101
-0
lines changed

3 files changed

+101
-0
lines changed

spiral-matrix/Readme.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# 54. Spiral Matrix
2+

spiral-matrix/main.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package leecode
2+
3+
func spiralOrder(matrix [][]int) []int {
4+
ret := []int{}
5+
if len(matrix) == 0 {
6+
return ret
7+
}
8+
m := len(matrix)
9+
n := len(matrix[0])
10+
x := 0
11+
y := 0
12+
for m > 0 && n > 0 {
13+
//if one row/column left, no circle can be formed
14+
if m == 1 {
15+
for i := 0; i < n; i++ {
16+
ret = append(ret, matrix[x][y])
17+
y++
18+
}
19+
break
20+
} else if n == 1 {
21+
for i := 0; i < m; i++ {
22+
ret = append(ret, matrix[x][y])
23+
x++
24+
}
25+
break
26+
}
27+
28+
//below, process a circle
29+
30+
//top - move right
31+
for i := 0; i < n-1; i++ {
32+
ret = append(ret, matrix[x][y])
33+
y++
34+
}
35+
36+
//right - move down
37+
for i := 0; i < m-1; i++ {
38+
ret = append(ret, matrix[x][y])
39+
x++
40+
}
41+
42+
//bottom - move left
43+
for i := 0; i < n-1; i++ {
44+
ret = append(ret, matrix[x][y])
45+
y--
46+
}
47+
48+
//left - move up
49+
for i := 0; i < m-1; i++ {
50+
ret = append(ret, matrix[x][y])
51+
x--
52+
}
53+
54+
x++
55+
y++
56+
m = m - 2
57+
n = n - 2
58+
}
59+
return ret
60+
}

spiral-matrix/main_test.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package leecode
2+
3+
import (
4+
"fmt"
5+
"reflect"
6+
"testing"
7+
)
8+
9+
func TestFindDiagonalOrder(t *testing.T) {
10+
testCases := []struct {
11+
Input [][]int
12+
Output []int
13+
}{
14+
{
15+
Input: [][]int{
16+
{1, 2, 3},
17+
{4, 5, 6},
18+
{7, 8, 9},
19+
},
20+
Output: []int{1, 2, 3, 6, 9, 8, 7, 4, 5},
21+
},
22+
{
23+
Input: [][]int{
24+
{1, 2, 3, 4},
25+
{5, 6, 7, 8},
26+
{9, 10, 11, 12},
27+
},
28+
Output: []int{1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7},
29+
},
30+
}
31+
for _, tc := range testCases {
32+
t.Run(fmt.Sprintf("%v:%d", tc.Input, tc.Output), func(t *testing.T) {
33+
actual := spiralOrder(tc.Input)
34+
if !reflect.DeepEqual(actual, tc.Output) {
35+
t.Errorf("expected %d, but get %d", tc.Output, actual)
36+
}
37+
})
38+
}
39+
}

0 commit comments

Comments
 (0)