Skip to content

1041. Robot Bounded In Circle 👍

  • Time:
  • Space:
 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;
    int y = 0;
    int d = 0;
    vector<vector<int>> directions{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    for (char instruction : instructions) {
      if (instruction == 'G') {
        x += directions[d][0];
        y += directions[d][1];
      } else if (instruction == 'L')
        d = (d + 3) % 4;
      else
        d = (d + 1) % 4;
    }

    return x == 0 && y == 0 || d > 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public boolean isRobotBounded(String instructions) {
    int x = 0;
    int y = 0;
    int d = 0;
    int[][] directions = new int[][] {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    for (char instruction : instructions.toCharArray()) {
      if (instruction == 'G') {
        x += directions[d][0];
        y += directions[d][1];
      } else if (instruction == 'L')
        d = (d + 3) % 4;
      else
        d = (d + 1) % 4;
    }

    return x == 0 && y == 0 || d > 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
  def isRobotBounded(self, instructions: str) -> bool:
    x = 0
    y = 0
    d = 0
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]

    for instruction in instructions:
      if instruction == 'G':
        x += directions[d][0]
        y += directions[d][1]
      elif instruction == 'L':
        d = (d + 3) % 4
      else:
        d = (d + 1) % 4

    return (x, y) == (0, 0) or d > 0