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



假设我有一个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中实现这一点?

  • 创建一个地图,根据当前方向给出下一个方向并移动。
  • 现在对于每个移动计算下一个方向,并检查它是否是一个有效的移动,如果它是然后返回下一个值,位置&
  • 如果移动无效,此解决方案抛出错误,您可以根据需要自定义错误处理。

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

注意,解决方案假设您有一个有效的网格(相同的编号)。

相关内容

  • 没有找到相关文章

最新更新