54. 螺旋矩阵
题目描述
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例
- 示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
- 示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
解题思路
思路:按层模拟
具体做法:
先从上、右、下、左四个方向一层一层的添加元素,如下图所示:
添加 matrix 剩余元素;
代码
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
if (!matrix.length) return [];
let rowStart = 0,
colStart = 0,
rowEnd = matrix.length - 1,
colEnd = matrix[0].length - 1,
res = [];
while (rowStart < rowEnd && colStart < colEnd) {
// 1.先添加上方的元素
for (let colCur = colStart; colCur < colEnd; colCur++) {
res.push(matrix[rowStart][colCur]);
}
// 2.添加右侧的元素
for (let rowCur = rowStart; rowCur < rowEnd; rowCur++) {
res.push(matrix[rowCur][colEnd]);
}
// 3.添加下方的元素
for (let colCur = colEnd; colCur > colStart; colCur--) {
res.push(matrix[rowEnd][colCur]);
}
// 4.添加左侧的元素
for (let rowCur = rowEnd; rowCur > rowStart; rowCur--) {
res.push(matrix[rowCur][colStart]);
}
rowStart++;
rowEnd--;
colStart++;
colEnd--;
}
// 添加剩余没有被添加的元素
while (colStart <= colEnd && rowStart === rowEnd) {
res.push(matrix[rowStart][colStart]);
colStart++;
}
while (rowStart <= rowEnd && colStart === colEnd) {
res.push(matrix[rowStart][colStart]);
rowStart++;
}
return res;
};