-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathleetcode0054.go
More file actions
37 lines (30 loc) · 759 Bytes
/
leetcode0054.go
File metadata and controls
37 lines (30 loc) · 759 Bytes
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
/*
LeetCode 54: https://leetcode.com/problems/spiral-matrix/
*/
package leetcode
func spiralOrder(matrix [][]int) []int {
result := make([]int, 0)
if len(matrix) == 0 || len(matrix[0]) == 0 {
return result
}
rows, cols := len(matrix), len(matrix[0])
for i := 0; 2*i < rows && 2*i < cols; i++ {
row, col := i, i
for ; col < cols-i; col++ {
result = append(result, matrix[row][col])
}
row, col = row+1, col-1
for ; row < rows-i; row++ {
result = append(result, matrix[row][col])
}
row, col = row-1, col-1
for ; row > i && col >= i; col-- {
result = append(result, matrix[row][col])
}
row, col = row-1, col+1
for ; 2*i+1 < cols && row > i; row-- {
result = append(result, matrix[row][col])
}
}
return result
}