1. 程式人生 > 實用技巧 >1041. Robot Bounded In Circle (M)

1041. Robot Bounded In Circle (M)

Robot Bounded In Circle (M)

題目

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.

Example 2:

Input: "GG"
Output: false
Explanation: 
The robot moves north indefinitely.

Example 3:

Input: "GL"
Output: true
Explanation: 
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

class Solution {
    public boolean isRobotBounded(String instructions) {
        int diffX = 0, diffY = 0;
        int dir = 0;
        for (char c : instructions.toCharArray()) {
            if (c == 'G') {
                diffX += dir == 1 ? -1 : dir == 3 ? 1 : 0;
                diffY += dir == 0 ? 1 : dir == 2 ? -1 : 0;
            } else if (c == 'L') {
                dir = (dir + 3) % 4;
            } else {
                dir = (dir + 1) % 4;
            }
        }
        return dir == 0 ? diffX == 0 && diffY == 0 : true;
    }
}