The problem is taken from LeetCode (Problem 874: Walking Robot Simulation). Here is the complete problem statement:
A robot is walking in a 2-dimensional grid starting from the origin point (0, 0). The robot can be controlled using commands represented by an integer array. Each command can be:
x
which means the robot moves forward x
units.-1
which means the robot turns 90 degrees to the right.-2
which means the robot turns 90 degrees to the left.Additionally, there are obstacles located on the grid that the robot must avoid. The obstacles are represented as a list of pairs of integers where each pair represents the coordinates of an obstacle (ox, oy)
.
The task is to find the maximum Euclidean distance squared from the origin that the robot can reach after executing all the commands.
(0, 0)
facing north.(x, y)
of an obstacle.Given the problem, we can break it down into the following steps:
(0, 0)
with the initial direction as “north”.-1
and -2
) to alter the direction.Here’s the complete implementation of the solution in Python:
def robotSim(commands, obstacles):
# Initial position and direction (north)
x, y = 0, 0
# Directions: north, east, south, west
directions = [ (0, 1), (1, 0), (0, -1), (-1, 0) ]
current_direction = 0
# Convert obstacles to a set of tuples for faster access
obstacles = set(map(tuple, obstacles))
max_distance = 0
for command in commands:
if command == -1:
# Turn right
current_direction = (current_direction + 1) % 4
elif command == -2:
# Turn left
current_direction = (current_direction - 1) % 4
else:
# Move forward 'command' steps
dx, dy = directions[current_direction]
for _ in range(command):
# Calculate the next position
next_x, next_y = x + dx, y + dy
# Check if the next position is an obstacle
if (next_x, next_y) in obstacles:
break
# Update the position
x, y = next_x, next_y
# Update the maximum distance
max_distance = max(max_distance, x*x + y*y)
return max_distance
# Example usage
commands = [4, -1, 3]
obstacles = []
print(robotSim(commands, obstacles)) # Output: 25
commands = [4, -1, 4, -2, 4]
obstacles = [[2, 4]]
print(robotSim(commands, obstacles)) # Output: 65
Initialization: O( | obstacles | ) for converting the obstacles list to a set. |
Thus, the overall time complexity is:
**O(N + | commands | ),** where N is the number of obstacles and | commands | is the length of the command list. Each step of the command involves checking if a position is an obstacle, which is O(1) with a set. |
This implementation ensures efficiency and effectively handles the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?