描述:

在无限的平面上,机器人最初位于 (0, 0) 处,面朝北方。机器人可以接受下列三条指令之一:

  • "G":直走 1 个单位
  • "L":左转 90 度
  • "R":右转 90 度

机器人按顺序执行指令 instructions,并一直重复它们。

只有在平面中存在环使得机器人永远无法离开时,返回 true。否则,返回 false

示例 1:

输入:"GGLLGG"
输出:true
解释:
机器人从 (0,0) 移动到 (0,2),转 180 度,然后回到 (0,0)。
重复这些指令,机器人将保持在以原点为中心,2 为半径的环中进行移动。

示例 2:

输入:"GG"
输出:false
解释:
机器人无限向北移动。

示例 3:

输入:"GL"
输出:true
解释:
机器人按 (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... 进行移动。

思路:循环四次后能回到原点(0,0)的符合
C++:
class Solution {
public:
    bool isRobotBounded(string instructions) {
        int a=0,b=0,c=0;//(a,b)表示坐标,c表示方向
        instructions+=instructions+instructions+instructions;
        for(int i=0;i<instructions.length();i++){
            if(instructions[i]=='G'){
                if(c==0)  b++;
                else if(c==1)  a--;
                else if(c==2)  b--;
                else a++;
            }else if(instructions[i]=='L'){
                if(c==3)  c=0;
                else c++;
            }else if(instructions[i]=='R'){
                if(c==0)  c=3;
                else c--;
            }
        }
        return a==0&&b==0;
    }
};
python:
class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        a=0
        b=0
        c=0
        instructions+=instructions+instructions+instructions
        for i in instructions:
            if i=='G':
                if c==0: b+=1
                elif c==1: a-=1
                elif c==2: b-=1
                else: a+=1
            elif i=='L':
                if c==3: c=0
                else: c+=1
            elif i=='R':
                if c==0: c=3
                else: c-=1
        return a==0 and b==0
posted on 2019-05-17 14:30  nibolyoung  阅读(517)  评论(0编辑  收藏  举报