力扣挑战赛第2天-No.59螺旋矩阵2

题目描述

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

spiral-matrix

如遇图片无法显示请访问 力扣-螺旋矩阵2

示例:

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

注意:

1 <= n <= 20

解法一:

模拟螺旋路径:与螺旋矩阵的解法一类似,从矩阵的左上角开始,初始向右,当路径超出界限或者进入之前访问过的位置时,顺时针旋转,进入下一个方向。

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
/**
* @param {number} n
* @return {number[][]}
*/
const generateMatrix = function (n) {
if (n === 1) {
return [[1]];
}
const result = new Array(n).fill(0).map(() => new Array(n).fill(0));
let num = 1;
let directionIndex = 0;
let row = 0;
let column = 0;
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
while (num <= n * n) {
result[row][column] = num++;
/* 获取下一个元素的行列坐标 */
let nextRow = row + directions[directionIndex][0];
let nextColumn = column + directions[directionIndex][1];
if (!(nextRow >= 0 && nextRow < n && nextColumn >= 0 && nextColumn < n && !result[nextRow][nextColumn])) {
directionIndex = (directionIndex + 1) % 4; // 顺时针旋转
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return result;
}

解法二

转圈遍历:与螺旋矩阵的解法二类似,四个方向循环进行遍历。

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
29
30
31
const generateMatrix = function (n) {
if (n === 1) {
return [[1]];
}
let left = 0;
let right = n - 1;
let top = 0;
let bottom = n - 1;
let res = new Array(n).fill(0).map(() => new Array(n).fill(0));
let num = 1;
/* 顺时针螺旋遍历 */
while (num <= n * n) {
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;
};
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020-2021 Sanmu
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信