机器人大冒险
难度:
标签:
题目描述
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后,走过的所有坐标' 是否会导致在存储时占用过多内存,特别是当 command 非常长时?
▷🦆
题解中的循环次数 'circle' 是使用 min(x // xi, y // yi) 计算得出的,这种方法是否能够准确反映在遇到障碍物前必须循环的次数?
▷