LeetCode-Python-5055. 困于环中的机器人

在无限的平面上,机器人最初位于 (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) -> ... 进行移动。

提示:

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

思路:

直接模拟,把指令执行四次,如果能回到原点,就说明在打圈。

class Solution(object):
    def isRobotBounded(self, ins):
        """
        :type instructions: str
        :rtype: bool
        """
        ins = ins * 4
        state = "N"
        xx, yy = 0, 0
        for i, x in enumerate(ins):
            if state == "N":
                if x == "G":
                    yy += 1
                elif x == "L":
                    state = "W"
                elif x == "R":
                    state = "E"
                    
            elif state == "W":
                if x == "G":
                    xx -= 1
                elif x == "L":
                    state = "S"
                elif x == "R":
                    state = "N"
                    
            elif state == "S":
                if x == "G":
                    yy -= 1
                elif x == "L":
                    state = "E"
                elif x == "R":
                    state = "W"
                    
            elif state == "E":
                if x == "G":
                    xx += 1
                elif x == "L":
                    state = "N"
                elif x == "R":
                    state = "S"
            print xx, yy, state
                    
        # print xx, yy
        return xx == 0 and yy == 0

猜你喜欢

转载自blog.csdn.net/qq_32424059/article/details/90140487