力扣挑战赛第1天-No.54螺旋矩阵

题目描述

给你一个 m 行 n 列的矩阵 matrix ,请按照顺时针螺旋顺序,返回矩阵中的所有元素。

spiral-matrix

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

示例:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]

注意:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

解法一

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

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
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const spiralOrder = function (matrix) {
if (!matrix.length || !matrix[0].length) {
return [];
}
const rows = matrix.length;
const columns = matrix[0].length;
const total = rows * columns;
const visited = new Array(rows).fill(0).map(() => new Array(columns).fill(false)); // 访问数组
const result = [];
let directionIndex = 0;
let row = 0;
let column = 0;
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
for (let i = 0; i < total; i++) {
result.push(matrix[row][column]);
visited[row][column] = true; // 为访问过的元素设置标志
/* 获取下一个元素的行列坐标 */
let nextRow = row + directions[directionIndex][0];
let nextColumn = column + directions[directionIndex][1];
if (!(nextRow >= 0 && nextRow < rows && nextColumn >= 0 && nextColumn < columns && !visited[nextRow][nextColumn])) {
directionIndex = (directionIndex + 1) % 4; // 顺时针旋转,利用 directions 和 directionIndex 控制元素行列坐标的变化
}
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
32
33
34
35
36
37
38
39
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const spiralOrder = function (matrix) {
if (!matrix.length || !matrix[0].length) {
return [];
}
let result = [];
let left = 0;
let right = matrix[0].length - 1;
let top = 0;
let bottom = matrix.length - 1;
let total = matrix.length * matrix[0].length;
/* 顺时针螺旋遍历 */
while (total >= 1) {
for (let i = left; i <= right && total >= 1; i++) {
result.push(matrix[top][i]);
total--;
}
top++;
for (let i = top; i <= bottom && total >= 1; i++) {
result.push(matrix[i][right]);
total--;
}
right--;
for (let i = right; i >= left && total >= 1; i--) {
result.push(matrix[bottom][i]);
total--;
}
bottom--;
for (let i = bottom; i >= top && total >= 1; i--) {
result.push(matrix[i][left]);
total--;
}
left++;
}
return result;
};
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 苏御
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信