# Walking Robot Simulation in Python

Suppose there is a robot on an infinite grid that starts at point (0, 0). It is facing towards north direction. Now the robot can receive one of three possible types of commands −

1. -2 to turn left 90 degrees
2. -1 to turn right 90 degrees
3. any value from 1 to 9 to move forward x units
4. There are some grid squares that are obstacles.

We also have another array called obstacle, this indicates the i-th obstacle is at grid point (obstacles[i], obstacles[i]), If the robot wants to move onto them, the robot stays on the previous grid square instead.

We have to find the square of the maximum Euclidean distance that the robot will be from the origin.

So, if the input is like commands = [4,-1,4,-2,4], obstacles = [[2,4]], then the output will be 65, as robot will be stuck at (1, 4) before turning left and going to (1, 8).

To solve this, we will follow these steps −

• position_offset := [(0, 1) ,(1, 0) ,(0, -1) ,(-1, 0) ]
• initialize x, y, direction, max_distance as 0
• for each command in commands, do
• if command is same as -2, then
• direction :=(direction - 1) mod 4
• otherwise when command is same as -1, then
• direction :=(direction + 1) mod 4
• otherwise,
• (x_off, y_off) :=position_offset[direction]
• while command is non-zero, do
• if (x + x_off, y + y_off) not in obstacles, then
• x := x + x_off
• y := y + y_off
• command := command - 1
• max_distance = maximum of max_distance, x^2 + y^2
• return max_distance

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def robotSim(self, commands, obstacles):
position_offset = [(0, 1), (1, 0), (0, -1), (-1, 0)]
obstacles = set(map(tuple, obstacles))
x, y, direction, max_distance = 0, 0, 0, 0
for command in commands:
if command == -2: direction = (direction - 1) % 4
elif command == -1: direction = (direction + 1) % 4
else:
x_off, y_off = position_offset[direction]
while command:
if (x + x_off, y + y_off) not in obstacles:
x += x_off
y += y_off
command -= 1
max_distance = max(max_distance, x**2 + y**2)
return max_distance
ob = Solution()
print(ob.robotSim([4,-1,4,-2,4],[[2,4]]))

## Input

[4,-1,4,-2,4],[[2,4]]

## Output

65