Robot Bounded In Circle Python Solution Leetcode

image
admin June 26, 2022

Competitive programming is essential and today we are going to solve the round bounded in circle leetcode problem. This problem appeared in amazon coding interview.

The question states that:- 

On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that:

The robot can receive one of three instructions:

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.

Solution:

Initially, we are facing north so we first loop through the string given. For each character, if we get G, then go straight 1 unit if L then calculates the direction by turning 90 degrees to the left, R then calculates the direction by turning 9 degrees to the right.

Last we return true if we are on 0,0 or the direction is not equal to n.

So why n because we are on n initially so if we repeat this process again and again then we will end up in the north direction so the circle is not formed.

Here is my python code :

class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        #for calculation movement
        def move(s,direction):
            if direction=="N":
                s[1]+=1
            elif direction=="E":
                s[0]+=1
            elif direction=="W":
                s[0]-=1
            else:
                s[1]-=1
        #for calculation direction when turn left    
        def get_directionl(curr_dir):
            if curr_dir=="N":
                return "W"
            elif curr_dir=="E":
                return "N"
            elif curr_dir=="W":
                return "S"
            else:
                return "E"
        #for calculation direction when turn right
        def get_directionr(curr_dir):
            if curr_dir=="N":
                return "E"
            elif curr_dir=="E":
                return "S"
            elif curr_dir=="W":
                return "N"
            else:
                return "W"
        
        s = [0,0]
        d  = "N"
        for i in instructions:
            if i=="G":
                move(s,d)
                
            elif i=="L":
                d = get_directionl(d)
            
            else:
                d = get_directionr(d)
        #return if s==[0,0]
        return (s[0]==0 and s[1]==0) or d!="N"

 

python python3 amazon competitive_programming