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

网格场景下查找下一个有效单元格的JavaScript实现优化方案

优化方案

核心优化思路

把方向和偏移量、转向规则做映射,完全替换冗余的if-else判断:

  • 按右转顺序定义四个方向的坐标偏移量,转向直接通过数组下标偏移实现,不用单独判断每个方向的转向逻辑
  • 坐标合法性判断统一写一套,不用按方向分别处理

具体实现代码

首先定义全局的方向映射常量:

// 按右转顺序排列:右 → 下 → 左 → 上,dx为x轴偏移,dy为y轴偏移
const DIRS = [
  { dir: 'right', dx: 0, dy: 1 },
  { dir: 'down', dx: 1, dy: 0 },
  { dir: 'left', dx: 0, dy: -1 },
  { dir: 'up', dx: -1, dy: 0 }
]

然后实现获取下一个位置的函数:

/**
 * 获取下一个移动位置
 * @param {Array} currentPos 当前位置,格式[x, y, direction]
 * @param {Array} grid 网格数组
 * @returns {Array} 下一个位置,格式[x, y, direction]
 */
function getNextPos(currentPos, grid) {
  const [x, y, curDir] = currentPos
  // 找到当前方向在DIRS中的下标
  const curDirIndex = DIRS.findIndex(item => item.dir === curDir)
  
  // 1. 计算当前方向前进一步的坐标
  const nextX = x + DIRS[curDirIndex].dx
  const nextY = y + DIRS[curDirIndex].dy
  
  // 2. 判断下一个坐标是否合法:在网格范围内,且不是墙体X
  const isValid = nextX >= 0 && nextX < grid.length && 
                  nextY >=0 && nextY < grid[nextX].length &&
                  grid[nextX][nextY] !== 'X'

  if (isValid) {
    // 合法就直接前进,方向不变
    return [nextX, nextY, curDir]
  } else {
    // 不合法就右转,转向后直接走一步匹配示例逻辑
    const newDirIndex = (curDirIndex + 1) % 4
    const newDir = DIRS[newDirIndex].dir
    const turnNextX = x + DIRS[newDirIndex].dx
    const turnNextY = y + DIRS[newDirIndex].dy
    return [turnNextX, turnNextY, newDir]
  }
}

其他优化建议

  • 位置表示可以从数组换成对象格式{x: number, y: number, direction: string},语义更清晰,避免出现x、y顺序写反的问题
  • 如果追求更高性能,可以把方向字符串换成数字枚举(0=右,1=下,2=左,3=上),省去每次查找方向下标的步骤,执行效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:06:00