题目: 给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
我的JavaScript解法:
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let matrix = new Array();
for(let i = 0; i < n; i++) {
matrix[i] = new Array(n);
}
let upperBound = 0, lowerBound = n -1;
let leftBound = 0, rightBound = n - 1;
let number = 1;
while(number <= n*n) {
if(upperBound <=lowerBound) {
for(let i = leftBound; i <= rightBound; i++) {
matrix[upperBound][i] = number++;
}
upperBound++;
}
if(leftBound <=rightBound) {
for(let i = upperBound; i <= lowerBound; i++) {
matrix[i][rightBound] = number++;
}
rightBound--;
}
if(upperBound <=lowerBound) {
for(let i = rightBound; i >= leftBound; i--) {
matrix[lowerBound][i] = number++;
}
lowerBound--;
}
if(leftBound <=rightBound) {
for(let i = lowerBound; i >= upperBound; i--) {
matrix[i][leftBound] = number++;
}
leftBound++;
}
}
return matrix;
};