-
Notifications
You must be signed in to change notification settings - Fork 116
/
Copy pathspiral_matrix.go
67 lines (65 loc) · 1019 Bytes
/
spiral_matrix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package spiral_matrix
const (
up string = "up"
down = "down"
left = "left"
right = "right"
)
func spiralOrder(matrix [][]int) []int {
ret := []int{}
if len(matrix) == 0 {
return ret
}
rows, cols := len(matrix), len(matrix[0])
status := right
i, j := 0, -1
for rows != 0 && cols != 0 {
switch status {
case right:
cnt := cols
for {
if cnt == 0 {
break
}
j, cnt = j+1, cnt-1
ret = append(ret, matrix[i][j])
}
rows--
status = down
case down:
cnt := rows
for {
if cnt == 0 {
break
}
i, cnt = i+1, cnt-1
ret = append(ret, matrix[i][j])
}
cols--
status = left
case left:
cnt := cols
for {
if cnt == 0 {
break
}
j, cnt = j-1, cnt-1
ret = append(ret, matrix[i][j])
}
rows--
status = up
case up:
cnt := rows
for {
if cnt == 0 {
break
}
i, cnt = i-1, cnt-1
ret = append(ret, matrix[i][j])
}
cols--
status = right
}
}
return ret
}