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.
My idea:循环一次后面北且有位移返回FALSE
class Solution: def isRobotBounded(self, instructions: str) -> bool: # 仅当循环一次后方向仍向北且有位移才不会困于环中,不然循环四次之后都会达到同一个状态(同方向,同坐标) x, y = 0, 0 dx, dy = 0, 1 for ins in instructions: if ins == 'L': dx, dy = -dy, dx elif ins == 'R': dx, dy = dy, -dx else: x, y = x+dx, y+dy return (dx, dy) != (0, 1) or (x, y) == (0, 0)
学习一下方向的这种写法,其实是向量,这样容易理解