Simulate Grid Rover Fleet Collision Logic
Arrays & HashingModel answerLast updated
Simulate the concurrent step-by-step navigation of multiple automated grid rovers, handling collisions, static obstacles, and grid bounds.
You are building the simulation module for an automated logistics center. The center operates on a 2D Cartesian grid of dimension width × height. Multiple autonomous vehicles (rovers) navigate this grid according to individual instruction strings.
Write a function simulate_rovers(grid_size, rovers, commands, obstacles) that computes and returns the final (x, y) coordinates of all rovers after all instructions have been processed.
Environment Rules
- Grid Setup: The grid spans from
x = 0tox = width - 1andy = 0toy = height - 1.(0, 0)is located at the top-left corner. - Move Directions: Commands consist of characters:
'U'(Up): decreasesyby 1 (y - 1)'D'(Down): increasesyby 1 (y + 1)'L'(Left): decreasesxby 1 (x - 1)'R'(Right): increasesxby 1 (x + 1)
- Impassable Terrain:
obstaclesis a set of fixed(x, y)locations that no rover can enter. - Collision Rules:
- Rovers move simultaneously in discrete turn steps.
- A rover cannot enter a space that was occupied by another rover at the beginning of the current step (no entering occupied space, even if the current occupant is trying to move away).
- If two or more rovers attempt to enter the exact same empty cell during the same turn, none of them move; all competing rovers abort their move and stay in their current positions for that turn.
- Invalid Moves: If an intended move lands out of bounds, hits an obstacle, or violates a collision rule, the rover remains stationary in its current location for that turn step.
Function Signature
def simulate_rovers(grid_size: tuple[int, int],
rovers: list[tuple[int, int]],
commands: list[str],
obstacles: set[tuple[int, int]]) -> list[tuple[int, int]]:
pass
Constraints
1 <= width, height <= 1001 <= len(rovers) <= 500 <= len(commands[i]) <= 100- Instruction strings can vary in length. A rover that runs out of instructions simply stays at its current location and continues to occupy its space.
Example
grid_size = (4, 4)
rovers = [(0, 0), (2, 0)]
commands = ["DRR", "L"]
obstacles = {(1, 1)}
# Output: [(2, 1), (1, 0)]
- Turn 1: Rover 0 moves
'D'to(0, 1). Rover 1 moves'L'to(1, 0). - Turn 2: Rover 0 attempts
'R'to(1, 1)but(1, 1)is an obstacle, so it stays at(0, 1). Rover 1 has no commands left, stays at(1, 0). - Turn 3: Rover 0 moves
'R'to(1, 1)? No,(1, 1)is an obstacle. It tries'R'from(0, 1)to(1, 1)- blocked! Wait, instructions for Rover 0 are"DRR":- Turn 1: R0 does
'D'->(0, 1). R1 does'L'->(1, 0). - Turn 2: R0 does
'R'-> targets(1, 1)which is an obstacle -> stays at(0, 1). - Turn 3: R0 does
'R'-> targets(1, 1)which is an obstacle -> stays at(0, 1).
- Turn 1: R0 does
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The key challenge in this problem is managing simultaneous state updates cleanly without introduce race conditions or order dependency.
To solve this correctly, we execute the simulation step-by-step using a Two-Phase Update per turn step:
- Snapshot Stage: At the beginning of turn $t$, snapshot all current rover positions into an
occupiedhash set. Also determine each rover's proposed target cell:- If a rover has exhausted its command string, its target is
None(it stays put). - If the target cell falls outside grid boundaries, is in the
obstaclesset, or is already present in the initialoccupiedset, the proposed move is invalid and evaluated asNone(the rover remains in place).
- If a rover has exhausted its command string, its target is
- Resolution Stage: Count the frequency of each proposed non-
Nonetarget cell across all rovers using a hash map or counter.- If a target cell is claimed by exactly one rover, that rover successfully moves to the target cell.
- If a target cell is claimed by multiple rovers (a contention conflict), all claimants remain in their original positions.
This approach guarantees $O(1)$ lookup for invalid moves and prevents race conditions (such as a rover tailgating into a cell another rover is vacating, or two rovers swapping positions in a single turn).
Python Source Code
from collections import Counter
def simulate_rovers(grid_size: tuple[int, int],
rovers: list[tuple[int, int]],
commands: list[str],
obstacles: set[tuple[int, int]]) -> list[tuple[int, int]]:
width, height = grid_size
move_map = {
'U': (0, -1),
'D': (0, 1),
'L': (-1, 0),
'R': (1, 0)
}
positions = list(rovers)
num_rovers = len(positions)
max_steps = max((len(cmd) for cmd in commands), default=0)
for step in range(max_steps):
# Snapshot of currently occupied cells at the start of the turn
occupied = set(positions)
proposed_targets = [None] * num_rovers
# Phase 1: Compute proposed valid moves
for i in range(num_rovers):
cmd_str = commands[i]
if step >= len(cmd_str):
continue
move = cmd_str[step]
dx, dy = move_map[move]
curr_x, curr_y = positions[i]
target = (curr_x + dx, curr_y + dy)
tx, ty = target
# Check grid bounds, static obstacles, and initial occupancy snapshot
if 0 <= tx < width and 0 <= ty < height:
if target not in obstacles and target not in occupied:
proposed_targets[i] = target
# Phase 2: Count target proposals to resolve collisions
target_counts = Counter(t for t in proposed_targets if t is not None)
# Phase 3: Apply positions
for i in range(num_rovers):
target = proposed_targets[i]
if target is not None and target_counts[target] == 1:
positions[i] = target
return positions
Complexity Analysis
- Time Complexity: $\mathcal{O}(S \cdot K)$, where $S$ is the maximum number of steps (max command length $\le 100$) and $K$ is the number of rovers ($\le 50$). In each turn step, we perform set lookups and
Counterupdates for $K$ rovers, taking $\mathcal{O}(1)$ average time per rover. - Space Complexity: $\mathcal{O}(K + |\text{obstacles}|)$. We store the initial positions, proposed moves, and occupied set of size at most $K$, alongside the obstacle set.