29.顺时针打印矩阵
题目描述
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]输入: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]0 <= matrix.length <= 100
0 <= matrix[i].length <= 100解题思路
代码
Last updated
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]输入: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]0 <= matrix.length <= 100
0 <= matrix[i].length <= 100Last updated
class Solution {
enum Dirction {
/// x + 1
case Right
/// y + 1
case Down
/// x - 1
case Left
/// y - 1
case Up
}
func spiralOrder(_ matrix: [[Int]]) -> [Int] {
var result: [Int] = []
let height = matrix.count
guard let first = matrix.first, height > 0 else {
return result
}
let width = first.count
var x = 0, y = 0
var dir: Dirction = .Right
var flags: [[Bool]] = Array(repeating: Array(repeating: false, count: width), count: height)
while x >= 0, y >= 0, x < width, y < height, result.count < width * height {
flags[y][x] = true
result.append(matrix[y][x])
switch dir {
case .Right:
if x + 1 < width, flags[y][x + 1] == false {
x += 1
}
else {
dir = .Down
y += 1
}
case .Down:
if y + 1 < height, flags[y + 1][x] == false {
y += 1
}
else {
dir = .Left
x -= 1
}
case .Left:
if x - 1 >= 0, x - 1 < width, flags[y][x - 1] == false {
x -= 1
}
else {
dir = .Up
y -= 1
}
case .Up:
if y - 1 >= 0, y - 1 < height, flags[y - 1][x] == false {
y -= 1
}
else {
dir = .Right
x += 1
}
}
}
return result
}
}