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

机器人返回起点最少指令数测试失败,求修正JavaScript代码

问题分析与修正方案

你的代码核心问题在于计算返回值的逻辑错误:仅通过坐标差的最大值取半来估算步数,完全忽略了机器人当前的朝向——调整朝向需要消耗指令,且只有当机器人转向某个特定方向后,才能通过直线移动回到起点。

错误原因

以输入"RF"为例:执行完指令后,机器人位于(1, 0),朝向右侧(方向1)。此时要回到起点,需要先转向左侧(需2次转弯指令),再向前走1步,总共3个指令。但你的代码计算Math.ceil(max(1,0)/2)=1,完全没考虑转向的成本。

修正后的代码

function solution(directions) {
    let x = 0;
    let y = 0;
    let direction = 0; // 0: 向上, 1: 向右, 2: 向下, 3: 向左
    const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]];

    for (let command of directions) {
        if (command === 'F') {
            const [dx, dy] = dirs[direction];
            x += dx;
            y += dy;
        } else if (command === 'L') {
            direction = (direction + 3) % 4; // 左转90度等价于加3模4
        } else if (command === 'R') {
            direction = (direction + 1) % 4; // 右转90度等价于加1模4
        }
        // 自动忽略非F/L/R的字符
    }

    // 已在起点直接返回0
    if (x === 0 && y === 0) {
        return 0;
    }

    let minCommands = Infinity;

    // 遍历所有可能的目标方向,计算每种情况的指令数
    for (let targetDir = 0; targetDir < 4; targetDir++) {
        const [dx, dy] = dirs[targetDir];
        let n;

        // 验证是否能通过转向当前目标方向后直线移动返回起点
        if (dx !== 0) {
            if (x % dx !== 0) continue;
            n = -x / dx;
            if (n <= 0 || y + n * dy !== 0) continue;
        } else {
            if (y % dy !== 0) continue;
            n = -y / dy;
            if (n <= 0 || x + n * dx !== 0) continue;
        }

        // 计算转向目标方向所需的最少指令数(左转/右转取最少次数)
        const turnCount = Math.min(Math.abs(targetDir - direction), 4 - Math.abs(targetDir - direction));
        const total = turnCount + n;

        if (total < minCommands) {
            minCommands = total;
        }
    }

    return minCommands;
}

修正逻辑说明

  1. 跟踪状态:先遍历输入指令,准确计算机器人最终的位置(x,y)和朝向direction。
  2. 起点判断:如果已经在起点,直接返回0。
  3. 遍历所有可能方向:对四个方向逐一检查:
    • 验证是否能通过转向该方向后,走n步直线回到起点(n必须为正整数)。
    • 计算转向该方向所需的最少指令数(转1次和转3次等价,取最小值)。
    • 累加转向次数和移动步数,记录所有合法情况中的最小值。

测试验证

  • 输入"RF":返回3(正确)
  • 输入"LFRFRFR":返回1(正确)
  • 输入"FxLxLxFx":返回0(正确)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 17:07:02