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]
func spiralOrder(matrix [][]int) []int {
if len(matrix) == 0 {
return []int{}
}
m := len(matrix)
n := len(matrix[0])
length := m * n
result := make([]int, length)
row, col, round, cnt := 0, 0, 0, 0
L:
for {
for ; col < n-round; col++ {
result[cnt] = matrix[row][col]
cnt++
if cnt == length {
break L
}
}
col--
for row = row + 1; row < m-round; row++ {
result[cnt] = matrix[row][col]
cnt++
if cnt == length {
break L
}
}
row--
for col = col - 1; col >= 0+round; col-- {
result[cnt] = matrix[row][col]
cnt++
if cnt == length {
break L
}
}
col++
for row = row - 1; row >= 1+round; row-- {
result[cnt] = matrix[row][col]
cnt++
if cnt == length {
break L
}
}
row++
col++
round++
}
return result
}