给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
func generateMatrix(_ n: Int) -> [[Int]] {
var result = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)
var top = 0, bottom = n - 1, left = 0, right = n - 1
var num = 1
while top <= bottom && left <= right {
for i in stride(from: left, through: right, by: 1) {
result[top][i] = num
num += 1
}
top += 1
for i in stride(from: top, through: bottom, by: 1) {
result[i][right] = num
num += 1
}
right -= 1
if top <= bottom {
for i in stride(from: right, through: left, by: -1) {
result[bottom][i] = num
num += 1
}
}
bottom -= 1
if left <= right {
for i in stride(from: bottom, through: top, by: -1) {
result[i][left] = num
num += 1
}
}
left += 1
}
return result
}
func generateMatrix_1(_ n: Int) -> [[Int]] {
var result = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)
let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
var row = 0, column = 0, current = 0
for i in 0..<n*n {
result[row][column] = i + 1
let nextRow = row + directions[current][0]
let nextColumn = column + directions[current][1]
if nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || result[nextRow][nextColumn] != 0 {
current = (current + 1) % 4
row = row + directions[current][0]
column = column + directions[current][1]
} else {
row = nextRow
column = nextColumn
}
}
return result
}
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
func spiralMatrix(_ matrix:[[Int]]) -> [Int] {
if matrix.count == 0 {return []}
let row = matrix.count - 1
let column = matrix[0].count - 1
var result = [Int]()
var left = 0, right = column
var top = 0, bottom = row
while left <= right && top <= bottom {
for i in stride(from: left, through: right, by: 1) {
result.append(matrix[top][i])
}
top += 1
// 上下符合的左右也必须符合答案才正确
if left <= right {
for i in stride(from: top, through: bottom, by: 1) {
result.append(matrix[i][right])
}
}
right -= 1
if top <= bottom {
for i in stride(from: right, through: left, by: -1) {
result.append(matrix[bottom][i])
}
}
bottom -= 1
if left <= right {
for i in stride(from: bottom, through: top, by: -1) {
result.append(matrix[i][left])
}
}
left += 1
}
return result
}