Problem
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.
"""
Solution -
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
state_transitions = {
'jl': '-i',
'-jl': 'i',
'il': 'j',
'-il': '-j',
'jr': 'i',
'-jr': '-i',
'ir': '-j',
'-ir': 'j'
}
curr_dir = 'j'
start = (0, 0)
for ins in instructions:
if ins == 'G':
if curr_dir == 'j':
start = (start[0], start[1] + 1 )
if curr_dir == '-j':
start = (start[0], start[1] - 1 )
if curr_dir == 'i':
start = (start[0] + 1, start[1] )
if curr_dir == '-i':
start = (start[0] - 1, start[1] )
if ins == 'L':
curr_dir = state_transitions[curr_dir+'l']
if ins == 'R':
curr_dir = state_transitions[curr_dir+'r']
if start == (0, 0):
return True
else:
if curr_dir != 'j':
return True
return False
Top comments (0)