|
| 1 | +#!/usr/bin/python3 |
| 2 | +""" |
| 3 | +On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions: |
| 4 | +
|
| 5 | +"G": go straight 1 unit; |
| 6 | +"L": turn 90 degrees to the left; |
| 7 | +"R": turn 90 degress to the right. |
| 8 | +The robot performs the instructions given in order, and repeats them forever. |
| 9 | +
|
| 10 | +Return true if and only if there exists a circle in the plane such that the |
| 11 | +robot never leaves the circle. |
| 12 | +
|
| 13 | +
|
| 14 | +
|
| 15 | +Example 1: |
| 16 | +
|
| 17 | +Input: "GGLLGG" |
| 18 | +Output: true |
| 19 | +Explanation: |
| 20 | +The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0). |
| 21 | +When repeating these instructions, the robot remains in the circle of radius 2 |
| 22 | +centered at the origin. |
| 23 | +Example 2: |
| 24 | +
|
| 25 | +Input: "GG" |
| 26 | +Output: false |
| 27 | +Explanation: |
| 28 | +The robot moves north indefinitely. |
| 29 | +Example 3: |
| 30 | +
|
| 31 | +Input: "GL" |
| 32 | +Output: true |
| 33 | +Explanation: |
| 34 | +The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ... |
| 35 | +
|
| 36 | +
|
| 37 | +Note: |
| 38 | +
|
| 39 | +1 <= instructions.length <= 100 |
| 40 | +instructions[i] is in {'G', 'L', 'R'} |
| 41 | +""" |
| 42 | + |
| 43 | +dirs = [(-1, 0), (0, 1), (1, 0), (0, -1)] |
| 44 | + |
| 45 | + |
| 46 | +class Solution: |
| 47 | + def isRobotBounded(self, instructions: str) -> bool: |
| 48 | + """ |
| 49 | + LL: op |
| 50 | + LLL: R |
| 51 | +
|
| 52 | + L, R 90 degree |
| 53 | + (GL) 90 needs 4 cycles to return back |
| 54 | + 180 needs 2 cycles |
| 55 | + 270 needs 4 cycles |
| 56 | +
|
| 57 | + After 4 cycles, check whether the robot is at (0, 0) |
| 58 | + """ |
| 59 | + x, y = 0, 0 |
| 60 | + i = 0 |
| 61 | + for _ in range(4): |
| 62 | + for cmd in instructions: |
| 63 | + if cmd == "G": |
| 64 | + dx, dy = dirs[i] |
| 65 | + x += dx |
| 66 | + y += dy |
| 67 | + elif cmd == "L": |
| 68 | + i = (i - 1) % 4 |
| 69 | + else: |
| 70 | + i = (i + 1) % 4 |
| 71 | + |
| 72 | + return x == 0 and y == 0 |
0 commit comments