我正在处理以下任务:
Given a sequence of moves for a robot, check if the sequence is circular or not. A sequence of moves is circular if first and last positions of robot are same.
A move can be on of the following.
G - Go one unit
L - Turn left
R - Turn right
Examples:
Input: path[] = "GLGLGLG"
Output: Given sequence of moves is circular
Input: path[] = "GLLG"
Output: Given sequence of moves is circular
The movements described in the input string are repeated for an infinite time. Your task is to find if there exists a circle, whose radius is some positive real number R,
such that the robot never leaves it. If such a circle exists return "YES" otherwise "NO"
我找到了这个任务的解决方案:
public class Circle {
String check(String commands) {
int initialX = 0;
int initialY = 0;
int x = 0;
int y = 0;
String direction = "north";
for (int i = 0; i < commands.length(); i++) {
if (direction.equals("north")) {
if (commands.charAt(i) == 'G') {
y++;
} else if (commands.charAt(i) == 'L') {
direction = "west";
} else if (commands.charAt(i) == 'R') {
direction = "east";
} else {
System.out.println("Wrong command");
}
} else if (direction.equals("east")) {
if (commands.charAt(i) == 'G') {
x++;
} else if (commands.charAt(i) == 'L') {
direction = "north";
} else if (commands.charAt(i) == 'R') {
direction = "south";
} else {
System.out.println("Wrong command");
}
} else if (direction.equals("south")) {
if (commands.charAt(i) == 'G') {
y--;
} else if (commands.charAt(i) == 'L') {
direction = "east";
} else if (commands.charAt(i) == 'R') {
direction = "west";
} else {
System.out.println("Wrong command");
}
} else if (direction.equals("west")) {
if (commands.charAt(i) == 'G') {
x--;
} else if (commands.charAt(i) == 'L') {
direction = "south";
} else if (commands.charAt(i) == 'R') {
direction = "north";
} else {
System.out.println("Wrong command");
}
}
}
if (direction.equals("north") && (((x-initialX)*(x-initialX) + (y-initialY)*(y-initialY)) > 0)) {
return "NO";
} else {
return "YES";
}
}
}
一切看起来都很完美,但我无法理解这种情况:
if (direction.equals("north") && (((x-initialX)*(x-initialX) + (y-initialY)*(y-initialY)) > 0))
你能帮我理解为什么我们需要在这种情况下返回 NO
吗,公式 && (((x-initialX)*(x-initialX) + (y -initialY)*(y-initialY)) > 0
表示?为什么条件只检查“北”方向而不检查其他方向。
最佳答案
最后一个条件可以缩短为:
if (direction.equals("north") && (x != 0 || y != 0))
这个条件意味着在给定的步骤序列之后,机器人有初始方向但没有初始位置。在这种情况下,此序列将机器人的位置移动 (x, y)
。这意味着在 n
次重复此序列后,机器人将位于 (n*x, n*y)
位置。当 x != 0 || 时,它不受任何半径的约束y != 0
。
当x
和y
都为零时,机器人在给定的步骤序列后具有初始方向和初始位置。这是一个循环,答案是"is"。
否则,机器人的方向在步骤序列后发生了变化。有两种可能:
- 方向已更改为相反(
南
)。假设在一系列步骤之后,机器人移动到坐标(x, y)
。但是当我们在相反的方向重复这个序列时,坐标将被(-x, -y)
改变,我们将返回到(0, 0)
初始坐标方向。 方向已更改为
西
或东
。在这种情况下,我们将在四个步骤之后以初始方向返回到初始位置。例如,假设在第一个序列之后方向更改为east
并且位置为(x, y)
:Direction | Coordinates -----------+-------------- north | (0, 0) east | (x, y) south | (x+y, y-x) west | (y, -x) north | (0, 0)
关于java - 检查机器人的给定移动序列是否在 Java 中是圆形的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47987823/