-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path1041.RobotBoundedInCircle.py
59 lines (51 loc) · 2.03 KB
/
1041.RobotBoundedInCircle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
"""
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:
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.
Example:
Input: "GG"
Output: false
Explanation:
The robot moves north indefinitely.
Example:
Input: "GL"
Output: true
Explanation:
The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
Note:
1. 1 <= instructions.length <= 100
2. instructions[i] is in {'G', 'L', 'R'}
"""
#Difficulty: Medium
#110 / 110 test cases passed.
#Runtime: 28 ms
#Memory Usage: 13.8 MB
#Runtime: 28 ms, faster than 82.06% of Python3 online submissions for Robot Bounded In Circle.
#Memory Usage: 13.8 MB, less than 62.31% of Python3 online submissions for Robot Bounded In Circle.
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
x, y = 0, 0
direction = 'N'
directions = {'N' : ['W', 'E'], 'S' : ['E', 'W'], 'E' : ['N', 'S'],'W' : ['S', 'N']}
positions = {'N' : [0, 1], 'S' : [0, -1], 'E' : [1, 0], 'W' : [-1, 0]}
for instruction in instructions:
if instruction == 'L':
direction = directions[direction][0]
elif instruction == 'R':
direction = directions[direction][1]
else:
x += positions[direction][0]
y += positions[direction][1]
return direction != 'N' or x == y == 0