题目描述:
给定一个包含 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]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix
这题目在之前的博客也有记录:
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function(matrix) {
if(matrix.length < 1) return [];
let res = [];
let printEdge = function(m, tr, tc, dr, dc) {
if(tr === dr) {
for(let i = tc; i <= dc; i++) {
res.push(m[tr][i]);
}
} else if(tc === dc) {
for(let j = tr; j <= dr; j++) {
res.push(m[j][tc]);
}
} else {
let curC = tc;
let curR = tr;
while(curC !== dc) { // 从左到右
res.push(m[tr][curC]);
curC++;
}
while(curR !== dr) { // 从右上到右下
res.push(m[curR][dc]);
curR++
}
while(curC !== tc) { // 从右下到左下
res.push(m[dr][curC])
curC--;
}
while(curR !== tr) { // 从左下到左上
res.push(m[curR][tc]);
curR--;
}
}
}
let tR = 0, tC = 0;
let dR = matrix.length - 1;
let dC = matrix[0].length - 1;
while(tR <= dR && tC <= dC) {
printEdge(matrix, tR++, tC++, dR--, dC--)
}
return res;
};