-
Notifications
You must be signed in to change notification settings - Fork 20
/
SpiralMatrix.go
103 lines (88 loc) · 1.79 KB
/
SpiralMatrix.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
94
95
96
97
98
99
100
101
102
103
package SpiralMatrix
//Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
//
//For example,
//Given the following matrix:
//
//[
//[ 1, 2, 3 ],
//[ 4, 5, 6 ],
//[ 7, 8, 9 ]
//]
//You should return [1,2,3,6,9,8,7,4,5].
//
//Accepted.
func spiralOrder(matrix [][]int) []int {
matrixLength := len(matrix)
if matrixLength == 0 {
return []int{}
}
matrixSingleLength := len(matrix[0])
if matrixSingleLength == 0 {
return []int{}
}
result := make([]int, 0)
added := make([][]bool, matrixLength)
for i := range added {
sub := make([]bool, matrixSingleLength)
for j := range sub {
sub[j] = false
}
added[i] = sub
}
if matrixLength == 1 {
for _, i := range matrix[0] {
result = append(result, i)
}
return result
}
if matrixSingleLength == 1 {
for _, ints := range matrix {
result = append(result, ints[0])
}
return result
}
centerX, centerY := matrixLength/2, matrixSingleLength/2
if matrixLength%2 == 0 {
centerX = (matrixLength - 1) / 2
}
if matrixSingleLength%2 == 0 {
centerY = (matrixSingleLength - 1) / 2
}
i, j, depth := 0, 0, 0
for ; i <= centerX && j <= centerY && depth <= centerX && depth <= centerY; {
j, i = depth, depth
for ; j < matrixSingleLength-depth; j++ {
if !added[i][j] {
result = append(result, matrix[i][j])
added[i][j] = true
}
}
j--
i++
for ; i < matrixLength-depth; i++ {
if !added[i][j] {
result = append(result, matrix[i][j])
added[i][j] = true
}
}
i--
j--
for ; j >= depth; j-- {
if !added[i][j] {
result = append(result, matrix[i][j])
added[i][j] = true
}
}
j++
i--
for ; i > depth; i-- {
if !added[i][j] {
result = append(result, matrix[i][j])
added[i][j] = true
}
}
depth++
}
return result
}