給你一個 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]()
// 循環(huán)直至邊界收縮完
while U <= D, L <= R {
// ??小提示
// `for i in X ... Y` 這種閉區(qū)間寫法在 `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
}
}