[LeetCode] Robot Bounded In Circle

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isRobotBounded(string instructions) {
int dir = 1, dx[4] {0, 1, 0, -1}, dy[4] {-1,0,1,0};
pair<int, int> p{0, 0};
for(auto& c : instructions) {
switch (c) {
case 'G': p.first += dy[dir], p.second += dx[dir]; break;
case 'L' : dir = (dir + 3) % 4; break;
case 'R' : dir = (dir + 1) % 4; break;
}
}

return !p.first && !p.second || dir != 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/01/PS/LeetCode/robot-bounded-in-circle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.