/** * @param {number[][]} matrix * @return {number[]} */ var spiralOrder = function (matrix) { const result = []; let top = 0, bottom = matrix.length - 1; let 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; };