算法:js实现将 n*n 二维数组转圈输出

114 阅读1分钟

思路

  1. 初始化边界:定义四个变量topbottomleftright,分别表示当前未遍历的矩阵的上、下、左、右边界。
  2. 循环遍历:使用一个while循环,只要top小于等于bottomleft小于等于right,就继续遍历。
  3. 从左到右:首先从左到右遍历矩阵的最上面一行,将元素添加到结果数组中,并将top边界下移。
  4. 从上到下:接着从上到下遍历矩阵的最右边一列,将元素添加到结果数组中,并将right边界左移。
  5. 从右到左:然后从右到左遍历矩阵的最下面一行,将元素添加到结果数组中,并将bottom边界上移。注意在这一步需要检查top是否小于等于bottom,避免重复遍历。
  6. 从下到上:最后从下到上遍历矩阵的最左边一列,将元素添加到结果数组中,并将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)); // 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]