Robot Bounded In Circle (LC1041)

  12 May 2019

By Wen Xu

leetcode algorithm

Problem description

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.
Example 2:

Input: "GG"
Output: false
Explanation: 
The robot moves north indefinetely.
Example 3:

Input: "GL"
Output: true
Explanation: 
The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...

Solution

  1. We notice after 4 sets of instructions, we always face the original direction (north). If at this time, we are at origin. Then we are bounded. If not, then we are unbounded.
  2. We can keep track of the current position and current direction. as (x, y), (directionx, directiony). Turn left, we just mutiply the direction by ((0,1),(-1,0)). Turn right, we just mutiply the direction by matrix ((0,-1),(1,0)). Move, we just add x + directionx, y + directiony

Below is my python implementation

class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        instructions = instructions * 4
        x, y = 0, 0
        directionx, directiony = 0, 1
        for c in instructions:
            #print(x,y,directionx, directiony)
            if c == 'G':
                x += directionx
                y += directiony
            elif c == 'L':
                newdirectionx = -directiony
                newdirectiony = directionx
                directionx = newdirectionx
                directiony = newdirectiony
            else:
                newdirectionx = directiony
                newdirectiony = -directionx
                directionx = newdirectionx
                directiony = newdirectiony
        return x == 0 and y == 0
				
comments powered by Disqus