LeetCode.54-螺旋矩阵

题目描述

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例1

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

示例2

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

提示

  • 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
if matrix.isEmpty || matrix[0].isEmpty { return [] }
var res = [Int]()
var left = 0
var top = 0
var bottom = matrix.count - 1
var right = matrix[0].count - 1

while left <= right && top <= bottom {
// 左上到右上
for col in left ... right {
res.append(matrix[top][col])
}
// 右上到右下
if top + 1 <= bottom { // for...in...写法需要判断top+1和bottom的大小
for row in top+1 ... bottom {
res.append(matrix[row][right])
}
}
// left == right || top == bottom是最后一行或最后一列
if left < right && top < bottom {
// 右下到左下
var col = right - 1
while col >= left {
res.append(matrix[bottom][col])
col -= 1
}

var row = bottom - 1
while row > top {
// 左下到左上
res.append(matrix[row][left])
row -= 1
}
}
left += 1
right -= 1
top += 1
bottom -= 1
}

return res
}