59. 螺旋矩阵 II
- 螺旋矩阵2是给定矩阵的维度n,然后按照螺旋矩阵的方式进行填充矩阵,最后返回矩阵。
- 螺旋矩阵这个是给定矩阵,按照顺时针螺旋的顺序进行遍历,得到最后的矩阵。(即进行上右下左的遍历)
- 不选择一条边从头遍历到底,则下一条边遍历的起点随之变化。所以选择不遍历到底,可以减小横向、竖向遍历之间的影响
- 对于本题,需要将最后中心的值补上
var generateMatrix = function(n) {
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0))
let num = 1
let left=0, right=n-1, top=0, bottom=n-1;
while(left < right && top < bottom){
for(let col=left; col<right; col++){
matrix[left][col] = num
num++
}
for(let row=top; row<bottom; row++){
matrix[row][right] = num
num++
}
for(let col=right; col>left; col--){
matrix[bottom][col] = num
num++
}
for(let row=bottom; row>top; row--){
matrix[row][left] = num
num++
}
left++
right--
top++
bottom--
}
if(left==right && top==bottom){
matrix[top][left] = num
}
return matrix
};