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 degress 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.
Example 1:
Input: "GGLLGG"
Output: true
Explanation:
The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
思路:这题应该是个hard难度,终点状态比较难想:
终点,只要是
第一:回到原点了,那肯定是cycle。
第二,如果面向还是north,但是坐标变了,不是0,0了,那么就是在shift,那么肯定不是cycle;其余状态肯定是cycle;
另外,跟robot那题一样,向左向右,dx一定要有顺序,顺时针,这样好判断direction;(direction + k) % 4;
class Solution {
public boolean isRobotBounded(String instructions) {
int[] pos = new int[] {0, 0};
int[] dx = {1, 0, -1, 0}; // 上左下右
int[] dy = {0, 1, 0, -1};
int dir = 0;
for(int i = 0; i < instructions.length(); i++) {
char c = instructions.charAt(i);
if(c == 'L') {
dir = (dir + 3) % 4;
} else if(c == 'R') {
dir = (dir + 1) % 4;
} else {
// c == 'G';
pos[0] = pos[0] + dx[dir];
pos[1] = pos[1] + dy[dir];
}
}
if(pos[0] == 0 && pos[1] == 0) {
return true;
}
if(dir == 0 && !(pos[0] == 0 && pos[1] == 0)) {
return false;
}
return true;
}
}