1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: bool isRobotBounded(string instructions) { int x = 0, y = 0, d = 0, dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; for (int i = 0; i < 4; ++i) { if (isBounded(x, y, d, dx, dy, instructions)) return true; } return false; }
bool isBounded(int &x, int &y, int &d, int dx[], int dy[], const string &ins) { for (char c : ins) { switch (c) { case 'L': d = (d + 3) % 4; break; case 'R': d = (d + 1) % 4; break; default: x += dx[d]; y += dy[d]; break; } } return x == 0 && y == 0; } };
|