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;
    }
}
posted @ 2020-09-17 21:04  墨云黑  阅读(303)  评论(0编辑  收藏  举报