如何根据当前位置找到二维数组中的下一个位置?

How to find the next position in a 2D array based on the current position?

假设我有一个包含 3 行和 4 列的数组 const arr = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 并且我给出了类似 ["straight", "right", "left"] 的输入并且初始位置是 arr[0][0] 并且初始方向是 "east".

[
 [1,  2,  3,  4],
 [5,  6,  7,  8],
 [9, 10, 11, 12]
]

从初始位置 "straight" 应该得到 2。然后从这里 "right" 应该给出 6 最后从这里 "left" 应该给出 7.

如何在 JavaScript 中实现此目的?

  • 创建一个地图,根据当前方向给出下一个方向并移动。
  • 现在为每一步计算下一个方向并检查它是否是一个有效的移动,如果是则return下一个值、位置和方向并为每一步重复此操作。
  • 如果移动在任何时候无效,此解决方案将引发错误,您可以根据需要自定义错误处理。

const nextDirMap = {
  north: { left: "west", right: "east", straight: "north" },
  south: { left: "east", right: "west", straight: "south" },
  east: { left: "north", right: "south", straight: "east" },
  west: { left: "south", right: "north", straight: "west" },
};

function getNextPos(grid, currPos, currDir, move) {
  const nextDir = nextDirMap[currDir][move];
  const [r, c] = currPos;
  const maxRowLength = grid.length;
  const maxColLength = grid[0].length;

  switch (nextDir) {
    case "north": {
      if (r <= 0) {
        throw "Unable to move";
      }
      return { val: grid[r - 1][c], pos: [r - 1, c], dir: "north" };
    }
    case "south": {
      if (r >= maxRowLength) {
        throw "Unable to move";
      }
      return { val: grid[r + 1][c], pos: [r + 1, c], dir: "south" };
    }
    case "east": {
      if (c >= maxColLength) {
        throw "Unable to move";
      }
      return { val: grid[r][c + 1], pos: [r, c + 1], dir: "east" };
    }
    case "west": {
      if (c <= 0) {
        throw "Unable to move";
      }
      return { val: grid[r][c - 1], pos: [r, c - 1], dir: "west" };
    }
  }
}

function solution(grid, initPos, initDir, moves) {
  let currPos = initPos;
  let currDir = initDir;
  let currVal;
  moves.forEach((move) => {
    let { val, pos, dir } = getNextPos(grid, currPos, currDir, move);
    currDir = dir;
    currPos = pos;
    currVal = val;
  });
  return currVal;
}

const res = solution(
  [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
  ],
  [0, 0],
  "east",
  ["straight", "right", "left"]
);

console.log(res); // 7

请注意,该解决方案假定您有一个有效的网格(所有行的列数相同)并且它至少有一行。