小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
题目
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
示例 1:
输入: n = 3 输出: [[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入: n = 1 输出: [[1]]
提示:
1 <= n <= 20
思路
将1~n^2的整数按顺时针螺旋方式填入n*n的矩阵中
本题与[螺旋矩阵I]有些相似,1中矩阵已知,将矩阵按顺时针读入一维数组,本题是已知一维数组顺时针
填入n*n矩阵中
本题矩阵必为方阵 [螺旋矩阵I]可以不是
- 初始化矩阵,初始位置1,初始的方向(向右)
- 定义顺时针的方向向量 [[0, 1], [1, 0], [0, -1], [-1, 0]] 右下左上(每次顺时针转90°)
- 遍历1~n^2,每次走一格,判断下一个点会不会超出四个边界点范围 或者已经遍历过这个元素时,调整当前方向 顺时针90°
- 更新当前行列的值 进入下次循环
var generateMatrix = function(n) {
const maxNum = n * n, res = new Array(n).fill(0).map(() => new Array(n).fill(0))
let row = 0, column = 0, curNum = 1, directionIndex = 0
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
while (curNum <= maxNum) {
res[row][column] = curNum
curNum++
const nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1]
if (nextRow < 0 || nextRow >= n || nextColumn < 0 || nextColumn >= n || res[nextRow][nextColumn] !== 0) {
directionIndex = (directionIndex + 1) % 4
}
row = row + directions[directionIndex][0]
column = column + directions[directionIndex][1]
}
return res
}
思路2
- r 生成 n * n 二维数组,r[y][x]表示第 y 行第 x 列,i 从 1 到 n的n次方 递增
- 按 →↓←↑ 顺序,碰撞 到边界 转向
- → 列 x++。↓ 行 y++。←列 x--。↑ 行 y--。填完 i 返回 r 即可
var generateMatrix = function(n) {
var b = [0, n - 1, 0, n - 1], x = 0, y = 0, i = 0, d = '→', r = new Array(n).fill(0).map(_=>new Array(n).fill(0))
while (i++ < Math.pow(n, 2)) {
d === '→' && (r[y][x++] = i, x === b[1] && (d = '↓', ++b[2])) ||
d === '↓' && (r[y++][x] = i, y === b[3] && (d = '←', b[1]--)) ||
d === '←' && (r[y][x--] = i, x === b[0] && (d = '↑', b[3]--)) ||
d === '↑' && (r[y--][x] = i, y === b[2] && (d = '→', ++b[0]))
}
return r
};