LeetCode 1041 Robot Bounded In Circle (Python)

Posted by 小明MaxMing on September 16, 2020

题目

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.

解题思路

经过一系列的操作,主要回到原点,或者朝向与最开始不同,就可以形成一个圈

代码

class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        x = y = 0
        d = (0, 1)
        for c in instructions:
            if c == 'G':
                x, y = x + d[0], y + d[1]
            elif c =='L':
                d = (-d[1], d[0])
            else:
                d = (d[1], -d[0])
        return (x == 0 and y == 0) or d != (0, 1)

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅