思路
- 初始化边界:定义四个变量
top、bottom、left和right,分别表示当前未遍历的矩阵的上、下、左、右边界。
- 循环遍历:使用一个
while循环,只要top小于等于bottom且left小于等于right,就继续遍历。
- 从左到右:首先从左到右遍历矩阵的最上面一行,将元素添加到结果数组中,并将
top边界下移。
- 从上到下:接着从上到下遍历矩阵的最右边一列,将元素添加到结果数组中,并将
right边界左移。
- 从右到左:然后从右到左遍历矩阵的最下面一行,将元素添加到结果数组中,并将
bottom边界上移。注意在这一步需要检查top是否小于等于bottom,避免重复遍历。
- 从下到上:最后从下到上遍历矩阵的最左边一列,将元素添加到结果数组中,并将
left边界右移。同样需要检查left是否小于等于right。
function spiralOrder(matrix) {
if (!matrix.length) return [];
const result = [];
let top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (let i = left; i <= right; i++){ result.push(matrix[top][i]);}
top++;
for (let i = top; i <= bottom; i++){ result.push(matrix[i][right]);}
right--;
if (top <= bottom) {
for (let i = right; i >= left; i--){ result.push(matrix[bottom][i]);}
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--){ result.push(matrix[i][left]);}
left++;
}
}
return result;
}
const matrix = [
[1, 2, 3],
[8, 9, 4],
[7, 6, 5]
];
console.log(spiralOrder(matrix));