Skip to main content

螺旋矩阵-ii

题目

给你一个正整数 n, 生成一个包含 1 所有元素, 且元素按顺时针顺序螺旋排列的 n * n 正方形矩阵 matrix.

示例

59-generate-matrix

输入: n = 3

输出: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]

提示:
  • 1 <= n <= 20

题解

54. 螺旋矩阵 的思路差不多, 通过模拟, 按照螺旋矩阵的路线进行遍历, 并给 matrix 的指定位置赋值即可.

/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
const matrix = new Array(n).fill(0).map(() => new Array(n).fill(0))

let top = 0,
right = n - 1,
bottom = n - 1,
left = 0

let val = 1

while (val <= n * n) {
for (let i = left; i <= right; i++, val++) matrix[top][i] = val
top++

for (let i = top; i <= bottom; i++, val++) matrix[i][right] = val
right--

for (let i = right; i >= left; i--, val++) matrix[bottom][i] = val
bottom--

for (let i = bottom; i >= top; i--, val++) matrix[i][left] = val
left++
}

return matrix
}