给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
思路
- 与 《螺旋矩阵》 思路一致
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| var generateMatrix = function (n) { const matrix = new Array(n).fill(null).map((_) => new Array(n).fill(0)) const [M, N] = [n, n] let curIndex = 1 let [top, bottom, left, right] = [0, M - 1, 0, N - 1] while (top <= bottom && left <= right) { for (let j = left; j <= right; ++j) { matrix[top][j] = curIndex++ } ++top for (let i = top; i <= bottom; ++i) { matrix[i][right] = curIndex++ } --right if (top > bottom || left > right) { break } for (let j = right; j >= left; --j) { matrix[bottom][j] = curIndex++ } --bottom for (let i = bottom; i >= top; --i) { matrix[i][left] = curIndex++ } ++left } return matrix }
|