题目

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

提示:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

题解

按层模拟

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
func spiralOrder(matrix [][]int) []int {
n, m := len(matrix), len(matrix[0])
top, bottom, left, right := 0, n, 0, m
ans := []int{}
for left < right && top < bottom {
for i := left; i < right; i++ {
ans = append(ans, matrix[top][i])
}
for i := top + 1; i < bottom; i++ {
ans = append(ans, matrix[i][right - 1])
}
if left < right - 1 && top < bottom - 1 {
for i := right - 2; i >= left; i-- {
ans = append(ans, matrix[bottom - 1][i])
}
for i := bottom - 2; i > top; i-- {
ans = append(ans, matrix[i][left])
}
}
left++
right--
top++
bottom--
}
return ans
}