这道题和另一道题目54. Spiral Matrix,很相似,我觉得会了那道题,这题是很简单的,下面是那题的博客链接
https://blog.csdn.net/dreamjay1997/article/details/87437861
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
题解:先建立一个轮廓,然后按题意一圈一圈填充值就行了,因为行和列都为n,所以结果是个矩形,这降低了难度
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let number = []
let total = 1
let top = 0, bottom = n, right = n
for(let i = 0; i < n; i ++) number[i] = []
while(total < n * n) {
for(let i = top; i < right - 1; i ++, total ++){
number[top][i] = total
}
for(let i = top; i < bottom - 1; i ++, total ++) {
number[i][right - 1] = total
}
for(let i = right - 1; i > top; i --, total ++) {
number[bottom - 1][i] = total
}
for(let i = bottom - 1; i > top; i --, total ++) {
number[i][top] = total
}
top ++
bottom --
right --
}
if(n % 2) {
let h = parseInt(n / 2)
number[h][h] = n * n
}
return number
};
Runtime: 72 ms, faster than 28.65% of JavaScript online submissions for Spiral Matrix II.
Memory Usage: 33.8 MB, less than 100.00% of JavaScript online submissions for Spiral Matrix II.