Leetcode 1041. Robot Bounded In Circle
On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
“G”: go straight 1 unit;
“L”: turn 90 degrees to the left;
“R”: turn 90 degrees to the right.
The robot performs the instructions given in order, and repeats them forever.
Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
思路:这题的难点在如何确定在什么情况下,机器人一定或一定不会回到原点。
- 最简单的就是走完一遍指令,回到原点
- 机器人最多走完几圈会回到原点
数学证明:如果机器人走完一遍指令不是朝北,那么机器人四圈以后一定会回到原点。
class Solution {
public boolean isRobotBounded(String instructions) {
int[][] directions = new int[][]{{0,1}, {1, 0}, {0,-1}, {-1, 0}};
int x = 0, y = 0;
int dir = 0;
for (char c : instructions.toCharArray()) {
if ( c == 'L') {
dir = (dir + 1) % 4;
} else if ( c == 'R') {
dir = (dir + 3) % 4;
} else {
x = x + directions[dir][0];
y = y + directions[dir][1];
}
}
return (x == 0 && y == 0) || (dir != 0);
}
}