51 lines
1.4 KiB
JavaScript

/**
* https://leetcode.cn/problems/spiral-matrix/?envType=study-plan-v2&envId=top-interview-150
* @param {number[][]} matrix
* @return {number[]}
*/
const spiralOrder = function (matrix) {
};
function f1(matrix) {
if (!matrix.length || !matrix[0].length) return []; // 矩阵中没有元素
const result = []; // 存放遍历的结果
// 定义四个边界的起始位置
let top = 0; // 上边界
let bottom = matrix.length - 1; // 下边界
let left = 0; // 左边界
let right = matrix[0].length - 1; // 右边界
// 开始模拟顺时针遍历,遍历结束的条件 top > bottom 或 left > right
while (left <= right && top <= bottom) {
// 从左到右遍历上边界
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;
}