zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    python计算文件MD5
    #每日一练 使用迭代器函数和初始种子值构建列表。
    python接收从CMD传过来的值
    ping IP,通与不通执行不同操作
    bat按回车执行命令
    adb执行简单命令,用于刷页面访问次数
    #每日一练 合并字典,并为每个字创建一个列表
    #每日一练 按提供函数,返回差异化
    #每日一练 根据过滤内容,把值分成两组
    #每日一练 根据索引对列表进行排序
  • 原文地址:https://www.cnblogs.com/mapoos/p/13687660.html
Copyright © 2011-2022 走看看