Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Walking Robot Simulation in Python
A walking robot simulation problem involves a robot on an infinite grid starting at point (0, 0) facing north. The robot receives commands to turn or move forward while avoiding obstacles.
Problem Description
The robot can receive three types of commands:
- -2: Turn left 90 degrees
- -1: Turn right 90 degrees
- 1-9: Move forward x units
Obstacles are represented as coordinates in an array. If the robot encounters an obstacle, it stops at the previous valid position. We need to find the maximum squared Euclidean distance from the origin.
Algorithm Approach
The solution uses direction mapping and step-by-step movement validation:
- Use direction vectors: North (0,1), East (1,0), South (0,-1), West (-1,0)
- Track current position (x, y) and direction index
- For each command, update direction or move step by step
- Check for obstacles before each step
- Track maximum distance squared from origin
Implementation
class Solution:
def robotSim(self, commands, obstacles):
# Direction vectors: North, East, South, West
position_offset = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# Convert obstacles to set for O(1) lookup
obstacles = set(map(tuple, obstacles))
# Initialize robot state
x, y, direction, max_distance = 0, 0, 0, 0
for command in commands:
if command == -2:
# Turn left
direction = (direction - 1) % 4
elif command == -1:
# Turn right
direction = (direction + 1) % 4
else:
# Move forward
x_off, y_off = position_offset[direction]
while command:
# Check if next position has obstacle
if (x + x_off, y + y_off) not in obstacles:
x += x_off
y += y_off
else:
# Stop if obstacle encountered
break
command -= 1
# Update maximum distance
max_distance = max(max_distance, x**2 + y**2)
return max_distance
# Test the solution
solution = Solution()
result = solution.robotSim([4, -1, 4, -2, 4], [[2, 4]])
print(f"Maximum distance squared: {result}")
Maximum distance squared: 65
Step-by-Step Execution
For commands = [4, -1, 4, -2, 4] and obstacles = [[2, 4]]:
def trace_robot_path():
position_offset = [(0, 1), (1, 0), (0, -1), (-1, 0)]
obstacles = {(2, 4)}
x, y, direction = 0, 0, 0
commands = [4, -1, 4, -2, 4]
directions = ["North", "East", "South", "West"]
print(f"Start: ({x}, {y}) facing {directions[direction]}")
for i, command in enumerate(commands):
print(f"\nCommand {i+1}: {command}")
if command == -2:
direction = (direction - 1) % 4
print(f"Turn left, now facing {directions[direction]}")
elif command == -1:
direction = (direction + 1) % 4
print(f"Turn right, now facing {directions[direction]}")
else:
x_off, y_off = position_offset[direction]
steps_taken = 0
for step in range(command):
next_pos = (x + x_off, y + y_off)
if next_pos not in obstacles:
x += x_off
y += y_off
steps_taken += 1
else:
print(f"Obstacle at {next_pos}, stopped after {steps_taken} steps")
break
print(f"Moved {steps_taken} steps to ({x}, {y})")
print(f"Distance squared: {x**2 + y**2}")
trace_robot_path()
Start: (0, 0) facing North Command 1: 4 Moved 4 steps to (0, 4) Distance squared: 16 Command 2: -1 Turn right, now facing East Command 3: 4 Moved 2 steps to (2, 4) Distance squared: 20 Command 4: -2 Turn left, now facing North Command 5: 4 Obstacle at (2, 4), stopped after 0 steps Moved 0 steps to (2, 4) Distance squared: 20
Key Points
- Direction Mapping: Use modulo arithmetic for direction changes
- Obstacle Detection: Convert obstacles to set for efficient lookup
- Step-by-Step Movement: Check obstacles before each individual step
- Distance Tracking: Update maximum distance after each movement command
Conclusion
The walking robot simulation uses direction vectors and obstacle checking to track the robot's path. The key insight is moving one step at a time while checking for obstacles, ensuring the robot stops before hitting any barrier.
