一、题目地址
https://leetcode-cn.com/problems/spiral-matrix-ii/
二、具体代码
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let array = Array.from(new Array(n), () => new Array(n).fill(0));
let num = 1;
let left = 0;
let right = n - 1;
let top = 0;
let bottom = n - 1;
let direction = 'right';
while(left <= right && top <= bottom) {
if(direction === 'right') {
for(let i=left; i<=right; i++) {
array[top][i] = num++;
}
top++;
direction = 'bottom';
}else if(direction === 'bottom'){
for(let i=top; i<=bottom; i++) {
array[i][right] = num++;
}
right--;
direction = 'left';
}else if(direction === 'left') {
for(let i=right; i>=left; i--) {
array[bottom][i] = num++;
}
bottom--;
direction = 'top';
}else if(direction === 'top') {
for(let i=bottom; i>=top; i--) {
array[i][left] = num++;
}
left++;
direction = 'right';
}
}
return array;
};