Sequential Robot Navigation on a Bounded Grid
Arrays & HashingAuto-graded · 19 test casesLast updated
Tests state-machine simulation with coordinate systems, directional rotation logic, boundary checking, and collision detection between sequentially deployed agents.
Problem Description
You are building a control system for autonomous robots operating on a rectangular grid floor. The grid extends from (0, 0) at the bottom-left to (width - 1, height - 1) at the top-right.
Each robot starts at a specified position (x, y) facing one of four cardinal directions: North ('N'), East ('E'), South ('S'), or West ('W'). Robots execute their instruction sequences one at a time: each robot completes all its commands before the next robot begins. After finishing, a robot remains stationary at its final position and becomes an obstacle for later robots.
Each robot receives a command string composed of:
'L': Turn 90 degrees left (counterclockwise). Example: North → West.'R': Turn 90 degrees right (clockwise). Example: North → East.'M': Advance one unit forward in the current facing direction.
Movement Rules
- If a forward move would place the robot outside the grid bounds (negative coordinates or
x >= widthory >= height), the move is skipped and the robot stays in place. - If a forward move would place the robot on a cell occupied by a previously completed robot, the move is skipped and the robot stays in place.
- Rotation commands always succeed.
- After a blocked move, the robot continues executing remaining commands normally.
Your task is to determine each robot's final position and orientation after all have completed their sequences.
Input
width: Integer, the grid width (x-axis extent).height: Integer, the grid height (y-axis extent).robots: A list of tuples(x, y, facing, instructions)where:x,y: Starting coordinates (integers).facing: Starting direction (string:'N','E','S', or'W').instructions: Command string (composed of'L','R','M'characters).
Output
Return a list of tuples (final_x, final_y, final_facing) representing each robot's ending state, in the order the robots were provided.
Constraints
1 ≤ width, height ≤ 10000 ≤ len(robots) ≤ 5000 ≤ len(instructions) ≤ 10,000for each robot- Starting positions satisfy
0 ≤ x < widthand0 ≤ y < height - No robot starts on a position occupied by a previously finished robot
Examples
Example 1
Input: navigate_robots(5, 5, [[1, 2, 'N', 'LMLMLMLMM'], [3, 3, 'E', 'MMRMMRMRRM']])
Output: [[1, 3, 'N'], [4, 1, 'E']]
Example 2
Input: navigate_robots(1, 1, [[0, 0, 'N', 'MMMMRMLLL']])
Output: [[0, 0, 'S']]
Example 3
Input: navigate_robots(5, 5, [])
Output: []
Hints
Hint 1
Represent the four cardinal directions in clockwise order so rotation becomes simple modular arithmetic on an index.
Hint 2
Precompute direction-to-movement deltas. Since (0, 0) is bottom-left, moving North increases y.
Hint 3
Track occupied cells in a set. Only add a robot's final position after it completes all commands, so it doesn't block itself.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a straightforward state-machine simulation where each robot maintains position (x, y) and a facing direction. The challenge lies in correctly modeling the coordinate system, rotation mechanics, boundary enforcement, and sequential obstacle placement.
Key Implementation Decisions:
-
Direction Encoding: Store the four cardinal directions in clockwise order:
['N', 'E', 'S', 'W']. This allows rotation commands to be implemented as index arithmetic: right turn is(index + 1) % 4, left turn is(index - 1) % 4. -
Movement Deltas: Precompute the displacement for each direction. Since
(0, 0)is the bottom-left corner, North increases y-coordinate:N → (0, 1),E → (1, 0),S → (0, -1),W → (-1, 0). -
Collision Tracking: Maintain a set of occupied cells. After a robot completes its instruction sequence, add its final position to this set. This ensures a robot never blocks itself during execution, and only finished robots act as obstacles for subsequent ones.
-
Move Validation: For each
'M'command, compute the target cell. Only commit the move if the target is within bounds (0 ≤ x < widthand0 ≤ y < height) and not occupied. If validation fails, the robot remains in place and continues processing remaining commands.
Why This Works:
- Rotations operate on a cyclic group of four states; indexing them sequentially makes both left and right turns simple modular operations.
- Checking boundaries and obstacles before updating position naturally implements the "ignore invalid moves" rule.
- Adding robots to the obstacle set only after they finish perfectly models the sequential deployment constraint.
Complexity Analysis:
- Time: O(C), where C is the total number of commands across all robots. Each command performs constant-time operations (arithmetic, set lookups).
- Space: O(R), where R is the number of robots. The obstacle set stores at most R positions, and the output list has R entries.
Solution Code
from typing import List, Tuple
def navigate_robots(width: int, height: int, robots: List[Tuple[int, int, str, str]]) -> List[Tuple[int, int, str]]:
headings = ['N', 'E', 'S', 'W']
heading_to_index = {h: i for i, h in enumerate(headings)}
movements = [(0, 1), (1, 0), (0, -1), (-1, 0)]
blocked_cells = set()
final_states = []
for x, y, facing, instructions in robots:
direction_idx = heading_to_index[facing]
for cmd in instructions:
if cmd == 'L':
direction_idx = (direction_idx - 1) % 4
elif cmd == 'R':
direction_idx = (direction_idx + 1) % 4
elif cmd == 'M':
dx, dy = movements[direction_idx]
candidate_x, candidate_y = x + dx, y + dy
if (0 <= candidate_x < width and
0 <= candidate_y < height and
(candidate_x, candidate_y) not in blocked_cells):
x, y = candidate_x, candidate_y
final_facing = headings[direction_idx]
final_states.append((x, y, final_facing))
blocked_cells.add((x, y))
return final_states