classSolution {enumDirction {/// x + 1case Right/// y + 1case Down/// x - 1case Left/// y - 1case Up }funcspiralOrder(_matrix: [[Int]]) -> [Int] {var result: [Int] = []let height = matrix.countguardlet first = matrix.first, height >0else {return result }let width = first.countvar x =0, y =0var dir: Dirction = .Rightvar 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 }}