题目描述
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] 输出: [1,2,3,6,9,8,7,4,5]
输入: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
思路
用一个游标按题意遍历二维数组即可。
解法
/**
* @param {number[][]} matrix
* @return {number[]}
*/
const spiralOrder = matrix => {
const result = [];
const boundary = {
left: 0,
top: 0,
bottom: matrix.length - 1,
right: (matrix[0] || 0).length - 1,
};
let direction = 'right';
let cursor = [0, 0];
const walk = direction => {
switch (direction) {
case 'right':
cursor[1] += 1;
break;
case 'bottom':
cursor[0] += 1;
break;
case 'left':
cursor[1] -= 1;
break;
case 'top':
cursor[0] -= 1;
break;
}
};
const overBoundary = () =>
cursor[1] > boundary.right ||
cursor[0] > boundary.bottom ||
cursor[1] < boundary.left ||
cursor[0] < boundary.top;
while (!overBoundary()) {
result.push(matrix[cursor[0]][cursor[1]]);
switch (direction) {
case 'right':
if (cursor[1] + 1 > boundary.right) {
boundary.top += 1;
direction = 'bottom';
}
break;
case 'bottom':
if (cursor[0] + 1 > boundary.bottom) {
boundary.right -= 1;
direction = 'left';
}
break;
case 'left':
if (cursor[1] - 1 < boundary.left) {
boundary.bottom -= 1;
direction = 'top';
}
break;
case 'top':
if (cursor[0] - 1 < boundary.top) {
boundary.left += 1;
direction = 'right';
}
break;
}
walk(direction);
}
return result;
};