题目

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:

  1. Input: "GGLLGG"
  2. Output: true
  3. Explanation:
  4. The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
  5. When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.

Example 2:

  1. Input: "GG"
  2. Output: false
  3. Explanation:
  4. The robot moves north indefinitely.

Example 3:

  1. Input: "GL"
  2. Output: true
  3. Explanation:
  4. The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...

Note:

  1. 1 <= instructions.length <= 100
  2. instructions[i] is in {'G', 'L', 'R'}

题意

给定一连串机器人行动的指令,判断机器人是否能保持在一个圆圈范围内活动。

思路

要让机器人保持在圆圈范围内活动,就要保持机器人会周期性的通过原点。当一个周期的指令执行完毕后,机器人会发生一个坐标的变化和一个指向方向的变化:如果结束方向指向北方,那么只有当结束位置也在原点时才能满足条件;如果结束方向指向南方,那么经过两个周期的指令一定能回到原点;如果结束方向指向西方或者东方,那么经过四个周期的指令一定能回到原点。因此只要对结束方向为北方这一种情况进行判断。


代码实现

Java

  1. class Solution {
  2. public boolean isRobotBounded(String instructions) {
  3. int diffX = 0, diffY = 0;
  4. int dir = 0;
  5. for (char c : instructions.toCharArray()) {
  6. if (c == 'G') {
  7. diffX += dir == 1 ? -1 : dir == 3 ? 1 : 0;
  8. diffY += dir == 0 ? 1 : dir == 2 ? -1 : 0;
  9. } else if (c == 'L') {
  10. dir = (dir + 3) % 4;
  11. } else {
  12. dir = (dir + 1) % 4;
  13. }
  14. }
  15. return dir == 0 ? diffX == 0 && diffY == 0 : true;
  16. }
  17. }