-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path54.spiral-matrix.go
149 lines (135 loc) · 2.42 KB
/
54.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/*
* @lc app=leetcode id=54 lang=golang
*
* [54] Spiral Matrix
*
* https://leetcode.com/problems/spiral-matrix/description/
*
* algorithms
* Medium (33.65%)
* Likes: 2277
* Dislikes: 561
* Total Accepted: 363.3K
* Total Submissions: 1.1M
* Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]'
*
* Given a matrix of m x n elements (m rows, n columns), return all elements of
* the matrix in spiral order.
*
* Example 1:
*
*
* Input:
* [
* [ 1, 2, 3 ],
* [ 4, 5, 6 ],
* [ 7, 8, 9 ]
* ]
* Output: [1,2,3,6,9,8,7,4,5]
*
*
* Example 2:
*
* Input:
* [
* [1, 2, 3, 4],
* [5, 6, 7, 8],
* [9,10,11,12]
* ]
* Output: [1,2,3,4,8,12,11,10,9,5,6,7]
*
*/
// @lc code=start
func spiralOrder(matrix [][]int) []int {
return spiralOrder2(matrix)
}
func spiralOrder2(matrix [][]int) []int {
if nil == matrix || len(matrix) == 0 {
return []int{}
}
row, col := len(matrix), len(matrix[0])
top, bottom, left, right := 0, row-1, 0, col-1
result, index := make([]int, row*col), 0 // make enough array
for {
// from left to right
for i := left; i <= right; i++ {
result[index] = matrix[top][i]
index++
}
top++
if top > bottom {
break
}
// from top to bottom
for i := top; i <= bottom; i++ {
result[index] = matrix[i][right]
index++
}
right--
if left > right {
break
}
// from right to left
for i := right; i >= left; i-- {
result[index] = matrix[bottom][i]
index++
}
bottom--
if top > bottom {
break
}
// from bottom to top
for i := bottom; i >= top; i-- {
result[index] = matrix[i][left]
index++
}
left++
if left > right {
break
}
}
return result
}
func spiralOrder1(matrix [][]int) []int {
if nil == matrix || len(matrix) == 0 {
return []int{}
}
result := make([]int, 0)
top, bottom, left, right := 0, len(matrix)-1, 0, len(matrix[0])-1
for {
// right
for i := left; i <= right; i++ {
result = append(result, matrix[top][i])
}
top++
if top > bottom {
break
}
// down
for i := top; i <= bottom; i++ {
result = append(result, matrix[i][right])
}
right--
if left > right {
break
}
// left
for i := right; i >= left; i-- {
result = append(result, matrix[bottom][i])
}
bottom--
if top > bottom {
break
}
// up
for i := bottom; i >= top; i-- {
result = append(result, matrix[i][left])
}
left++
if left > right {
break
}
}
return result
}
// @lc code=end