leetcode
leetcode 2751 ~ 2800
机器人大冒险

机器人大冒险

难度:

标签:

题目描述

English description is not available. Please switch to Chinese.

代码结果

运行时间: 31 ms, 内存: 16.5 MB


/*
 * Problem: A robot starts at (0, 0) and can follow a repeating command sequence to move on a 2D plane.
 * The command sequence consists of 'U' (up) and 'R' (right) moves. 
 * There are obstacles on the plane that the robot must avoid.
 * Given the target coordinates (x, y), determine if the robot can reach the target without hitting any obstacles.
 */

import java.util.Arrays;

public class RobotPathStream {
    public boolean canReach(String command, int[][] obstacles, int x, int y) {
        // Calculate the end position after one full cycle of the command
        int cycleX = 0, cycleY = 0;
        for (char c : command.toCharArray()) {
            if (c == 'U') cycleY++;
            else if (c == 'R') cycleX++;
        }

        // Helper function to check if a position is reachable without hitting obstacles
        boolean isReachable(int tx, int ty) {
            if (tx < 0 || ty < 0) return false;
            int cycles = Math.min(tx / cycleX, ty / cycleY);
            int remainingX = tx - cycles * cycleX;
            int remainingY = ty - cycles * cycleY;

            return command.chars().anyMatch(c -> {
                if (c == 'U') remainingY--;
                else if (c == 'R') remainingX--;
                return remainingX == 0 && remainingY == 0;
            });
        }

        // Check if the target is reachable
        if (!isReachable(x, y)) return false;

        // Check if any obstacle is on the path
        return Arrays.stream(obstacles).noneMatch(obstacle -> isReachable(obstacle[0], obstacle[1]));
    }
}

解释

方法:

该题解采用的是模拟机器人行走的方式。首先,根据输入的command,模拟机器人第一次执行完这串指令后经过的所有坐标点,并存储起来。接着,利用目标点和障碍点的坐标,计算机器人在到达这些点前需要循环执行指令的次数,以判断是否能够到达目标点,以及是否会碰到障碍物。如果机器人在到达目标点之前碰到任何障碍物,则返回False;如果能够安全到达目标点,则返回True。

时间复杂度:

O(n + m)

空间复杂度:

O(n)

代码细节讲解

🦆
在解决方案中,如何确保计算 'circle' 时不会因为除数为零(xi或yi为0)导致错误?
在题解的算法中,假设command中至少含有一个'R'和一个'U',因此xi和yi在执行完一次command后不会为0。然而,如果command中仅包含'R'或'U',那么xi或yi可能为0。在实际实现中,应当在代码中检查xi和yi是否为0,如果是,则需要特殊处理或者返回错误信息。例如,如果xi为0(即command中没有'R'),只有当目标点x坐标也为0时,机器人才可能到达目标点或考虑障碍物,否则直接返回False。同理,如果yi为0,处理方法也相同。
🦆
题解中提到的 '第一次执行完command后,走过的所有坐标' 是否会导致在存储时占用过多内存,特别是当 command 非常长时?
确实,如果command非常长,存储每个经过的坐标点会消耗大量内存。这种问题可以通过优化数据结构来减少内存使用。例如,可以使用哈希集合(HashSet)来存储坐标,而不是列表(List)。这样可以提高检查坐标是否存在的效率,同时相比列表,哈希集合可以减少一些内存占用。另外,考虑到机器人路径的周期性,可以只存储一个周期内的坐标点,而不是整个command执行过程中的所有坐标。
🦆
题解中的循环次数 'circle' 是使用 min(x // xi, y // yi) 计算得出的,这种方法是否能够准确反映在遇到障碍物前必须循环的次数?
使用 min(x // xi, y // yi) 来计算循环次数是基于假设机器人沿着最初的路径直线前进,并在每个周期结束时检查其位置是否达到或超过目标点。这种方法能够有效地计算到达目标点的最小循环次数,但对于障碍物的检查可能不够准确,因为障碍物可能出现在路径的任何位置。因此,对于每个障碍物,都需要独立计算其所需的循环次数,并检查在该循环次数下,机器人是否会经过障碍物的坐标。如果任一障碍物位于机器人到达目标点之前的路径上,则返回False。这种方法确保了在到达目标点之前,任何障碍物都会被考虑进去。

相关问题