You need to enable JavaScript to run this app. JavaScript 如何根据矩阵元素的方向标记移动重排元素
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript 如何根据矩阵元素的方向标记移动重排元素

矩阵方向位移重排实现

初始定义的矩阵

let m = [
  ["0",      "0",      "S",       "S",       "0",   "0"],
  ["0",      "S", "D^left", "D^right",       "S",   "0"],
  ["S", "D^left", "Dvleft", "Dvright", "D^right",   "S"],
  ["S", "Dvleft",   "D<up",    "D>up", "Dvright",   "S"],
  ["0",      "S", "D<down",  "D>down",       "S",   "0"],
  ["0",      "0",      "S",       "S",       "0",   "0"]
];

重排规则

  • 所有带方向标记的元素,按照标记指定的方向移动1格
  • 原矩阵中值为"0"的位置保持固定,不被其他元素覆盖
  • 其余未被固定0、移动后元素覆盖的位置,统一填充为"S"

期望输出矩阵

m = [
  ["0",      "0",      "S",      "S",       "0",       "0"],
  ["0", "D^left",      "S",      "S", "D^right",       "0"],
  ["D^left", "Dvleft", "D<up", "D>up", "Dvright", "D^right"],
  ["Dvleft",      "S",      "S",      "S",       "S", "Dvright"],
  ["0",      "S",      "S",      "S",       "S",       "0"],
  ["0",      "0", "D<down", "D>down",       "0",       "0"]
];

原实现存在的问题

直接在原矩阵上边遍历边修改元素位置的方式,会引发两个核心问题:

  • 已经移动到新位置的元素,会在后续遍历到该位置时被重复识别,按照自身方向再次移动,导致最终位置偏移
  • 原位置的填充操作会覆盖其他尚未遍历到的待移动元素,造成元素丢失、位置错乱

实现思路

  1. 新建与原矩阵尺寸完全一致的结果矩阵,先遍历原矩阵,把所有固定的"0"位置原样复制到结果矩阵,其余位置初始填充为"S"
  2. 遍历原矩阵的每个元素,对带方向标记的元素,根据标记内容计算目标位置的行列偏移量,直接将元素写入结果矩阵的对应位置
  3. 整个过程不修改原矩阵内容,从根源上避免遍历过程中的状态干扰

参考实现代码

function rearrangeMatrix(matrix) {
  const rowCount = matrix.length;
  const colCount = matrix[0].length;
  // 初始化结果矩阵,默认填充"S"
  const result = Array.from({length: rowCount}, () => Array(colCount).fill("S"));
  // 复制固定的"0"位置
  for (let row = 0; row < rowCount; row++) {
    for (let col = 0; col < colCount; col++) {
      if (matrix[row][col] === "0") {
        result[row][col] = "0";
      }
    }
  }
  // 处理带方向标记的元素,写入目标位置
  for (let row = 0; row < rowCount; row++) {
    for (let col = 0; col < colCount; col++) {
      const item = matrix[row][col];
      if (!item.startsWith("D")) continue;
      let targetRow = row;
      let targetCol = col;
      // 根据标记计算偏移量
      if (item.includes("left")) targetCol -= 1;
      if (item.includes("right")) targetCol += 1;
      if (item.includes("up")) targetRow -= 1;
      if (item.includes("down")) targetRow += 1;
      // 边界校验,确保目标位置有效
      if (targetRow >= 0 && targetRow < rowCount && targetCol >=0 && targetCol < colCount) {
        result[targetRow][targetCol] = item;
      }
    }
  }
  return result;
}
// 执行重排
const newMatrix = rearrangeMatrix(m);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.10 23:45:08