1、原题
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
2、思路
理解了这个题的逻辑,方法就很简单了,主要还是确定上下左右边界,一条边一条边填充。
3、代码
class Solution {
func generateMatrix(_ n: Int) -> [[Int]] {
// 定义上下左右边界,
var top = 0
var right = n - 1
var bottom = n - 1
var left = 0
// 返回结果
var result = [[Int]](repeating: [Int](repeating: 0, count: n), count:n)
// 初始值从1开始
var num = 1
// 结束值
let target = n * n
while num <= target {
// 从左到右从上倒下开始排列
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
for i in stride(from: right, through: left, by: -1) {
result[bottom][i] = num
num += 1
}
bottom -= 1
for i in stride(from: bottom, through: top, by: -1) {
result[i][left] = num
num += 1
}
left += 1
}
return result
}
}