给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
LeetCode: https://leetcode.cn/problems/trapping-rain-water/submissions/
class Solution {
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
// m行 n列
let m = matrix.count
let n = matrix[0].count
// 上下左右边界
var U = 0
var D = m - 1
var L = 0
var R = n - 1
// 结果
var res = [Int]()
// 循环直至边界收缩完
while U <= D, L <= R {
// ⚠️小提示
// `for i in X ... Y` 这种闭区间写法在 `Y > X` 时,运行会抛出Range异常
// 解决办法是在末尾加上 `where X <= Y`, 如:
// `for i in X ... Y where X <= Y`
// `stride(from: X, through: Y, by: 1) where X <= Y`
// print("--")
// 左 -> 右
for col in stride(from: L, through: R, by: 1) where L <= R && U <= D {
res.append(matrix[U][col])
}
U += 1 // 收缩上边界
// print(res)
// 上 -> 下
for row in stride(from: U, through: D, by: 1) where L <= R && U <= D {
res.append(matrix[row][R])
}
R -= 1 // 收缩右边界
// print(res)
// 右 -> 左
for col in stride(from: R, through: L, by: -1) where L <= R && U <= D {
res.append(matrix[D][col])
}
D -= 1 // 收缩下边界
// print(res)
// 下 -> 上
for row in stride(from: D, through: U, by: -1) where L <= R && U <= D {
res.append(matrix[row][L])
}
L += 1 // 收缩左边界
// print(res)
}
return res
}
}