-
Notifications
You must be signed in to change notification settings - Fork 0
/
spiral_matrix.go
93 lines (81 loc) · 1.37 KB
/
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package array
func SpiralMatrix(matrix [][]int) []int {
const (
LEFT = iota
RIGHT
UP
DOWN
)
iterations := len(matrix[0]) * len(matrix)
direction := RIGHT
col := 0
row := 0
passedRowsMin := -1
passedColsMin := -1
passedColsMax := len(matrix[0]) - 1
passedRowsMax := len(matrix) - 1
result := make([]int, 0)
var down, right, left, up func()
right = func() {
if col+1 <= passedColsMax {
col = col + 1
} else {
direction = DOWN
if passedRowsMin-passedRowsMax == 0 {
return
}
passedRowsMin = passedRowsMin + 1
down()
}
}
left = func() {
if col-1 > passedColsMin {
col = col - 1
} else {
direction = UP
if passedRowsMin-passedRowsMax == 0 {
return
}
passedRowsMax = passedRowsMax - 1
up()
}
}
down = func() {
if row+1 <= passedRowsMax {
row = row + 1
} else {
direction = LEFT
if passedColsMax-passedColsMin == 0 {
return
}
passedColsMax = passedColsMax - 1
left()
}
}
up = func() {
if row-1 > passedRowsMin {
row = row - 1
} else {
direction = RIGHT
if passedColsMax-passedColsMin == 0 {
return
}
passedColsMin = passedColsMin + 1
right()
}
}
for i := 0; i < iterations; i++ {
result = append(result, matrix[row][col])
switch direction {
case LEFT:
left()
case RIGHT:
right()
case DOWN:
down()
case UP:
up()
}
}
return result
}