You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中二维数组(Matrix)90度旋转,求其他实现方法

二维数组旋转90度的其他实现方法

你的现有方案(转置+反转每行)是顺时针旋转90度的经典原地实现,下面还有几种不同的可行方法:

方法1:原地逐层旋转

不需要先转置,直接按矩阵的层来处理,每层的四个对应位置元素互相交换,适合需要严格原地修改且不想拆分步骤的场景。

const matrix = [[1,2,3],[4,5,6],[7,8,9]];

function rotateInPlace(matrix) {
  const n = matrix.length;
  // 遍历每一层
  for (let layer = 0; layer < Math.floor(n / 2); layer++) {
    const first = layer;
    const last = n - 1 - layer;
    // 处理当前层的每个元素
    for (let i = first; i < last; i++) {
      const offset = i - first;
      // 保存顶部元素
      const top = matrix[first][i];
      // 左 -> 顶
      matrix[first][i] = matrix[last - offset][first];
      // 底 -> 左
      matrix[last - offset][first] = matrix[last][last - offset];
      // 右 -> 底
      matrix[last][last - offset] = matrix[i][last];
      // 顶 -> 右
      matrix[i][last] = top;
    }
  }
}

rotateInPlace(matrix);
matrix.forEach(row => console.log(...row));

方法2:创建新矩阵(非原地,逻辑直观)

直接根据顺时针旋转的坐标映射关系生成新矩阵,不需要修改原数组,适合需要保留原矩阵的场景。

顺时针90度的坐标映射规则:原矩阵中matrix[i][j]的元素,会出现在新矩阵的newMatrix[j][n-1-i]位置(n为矩阵边长)。

const matrix = [[1,2,3],[4,5,6],[7,8,9]];

function rotateNewMatrix(matrix) {
  const n = matrix.length;
  const newMatrix = Array.from({ length: n }, () => []);
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      newMatrix[j][n - 1 - i] = matrix[i][j];
    }
  }
  return newMatrix;
}

const rotated = rotateNewMatrix(matrix);
rotated.forEach(row => console.log(...row));

方法3:利用数组高阶方法的简洁实现(非原地)

通过数组的map、reverse等方法组合,用简洁的代码完成旋转,可读性高。

const matrix = [[1,2,3],[4,5,6],[7,8,9]];

const rotated = matrix[0].map((_, colIndex) => 
  matrix.map(row => row[colIndex]).reverse()
);

rotated.forEach(row => console.log(...row));

思路:先按列提取原矩阵的每一列(matrix.map(row => row[colIndex])),再将提取出的列反转,就得到了旋转后的行。

内容的提问来源于stack exchange,提问作者Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 01:20:21