题目:
给你一个正整数
n
,生成一个包含1
到n2
所有元素,且元素按顺时针顺序螺旋排列的n x n
正方形矩阵matrix
。来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]
示例2:
输入:n = 1
输出:[[1]]
提示:
· 1 <= n <= 20
解法:
确定上下左右边界,在边界内遍历
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function(n) {
let top = 0, bottom = n - 1, left = 0, right = n - 1;
let num = 1;
const res = [];
for (let i = 0; i < n; i++) {
res.push([]);
}
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++) {
res[top][i] = num++;
}
top++;
for (let i = top; i <= bottom; i++) {
res[i][right] = num++;
}
right--;
for (let i = right; i >= left; i--) {
res[bottom][i] = num++;
}
bottom--;
for (let i = bottom; i >= top; i--) {
res[i][left] = num++;
}
left++;
}
return res;
};