Rover on a Walled Floor Plan with Blocked Cells
Arrays & HashingAuto-graded · 17 test casesLast updated
Simulate a rover on a bounded rectangular grid that turns, steps forward, and steps backward, skipping any step that leaves the grid or enters a blocked cell.
A rover drives around a rectangular floor plan. Some cells are blocked by crates. Your job is to replay a string of instructions and report where the rover ends up and which way it faces.
Floor plan
The floor has cols columns and rows rows. Cell (0, 0) is the bottom-left corner and cell (cols - 1, rows - 1) is the top-right corner. A cell (x, y) is on the floor only if 0 <= x < cols and 0 <= y < rows.
The rover begins at a given cell and faces one of four compass directions:
"N"points toward increasingy."E"points toward increasingx."S"points toward decreasingy."W"points toward decreasingx.
Instructions
The instruction string is read one character at a time, from left to right:
L: rotate 90 degrees counter-clockwise in place (for exampleNbecomesW).R: rotate 90 degrees clockwise in place (for exampleNbecomesE).M: advance one cell in the direction the rover currently faces.B: reverse one cell, i.e. step opposite to the facing direction. The facing direction stays the same.
Blocked steps
- If an
MorBstep would take the rover off the floor, the step is skipped and the rover stays where it is. - If an
MorBstep would take the rover onto a crate cell, the step is skipped and the rover stays where it is. - A skipped step does not stop the run. Processing simply continues with the next instruction.
- Rotations (
L,R) always succeed.
Task
Implement the function so that it processes every instruction and returns the final state as a list [x, y, direction], where direction is one of the strings "N", "E", "S", "W".
Input format
cols: number of columns (width of the floor).rows: number of rows (height of the floor).start: a list[x, y, direction]giving the initial cell and facing.crates: a list of[cx, cy]pairs, each a blocked cell.instructions: the string of commands.
Constraints
1 <= cols, rows <= 10^4startis[x, y, direction]with0 <= x < cols,0 <= y < rows, and direction in{"N", "E", "S", "W"}.0 <= len(crates) <= 10^5- Every crate
[cx, cy]satisfies0 <= cx < colsand0 <= cy < rows. Duplicate crates may appear. - The starting cell is never a crate.
0 <= len(instructions) <= 10^5instructionscontains only the charactersL,R,M,B.
Examples
Example 1
Input: run_rover(5, 5, [1, 1, 'N'], [[1, 3]], 'MMRMB')
Output: [1, 2, 'E']
Example 2
Input: run_rover(3, 3, [0, 0, 'S'], [], 'MLM')
Output: [1, 0, 'E']
Hints
Hint 1
The rover's whole state is just its x, y and facing. Each instruction can be applied to that state in constant time, so there is no need to build the grid (it can have 10^8 cells).
Hint 2
Checking whether a target cell holds a crate by scanning the list would be too slow for 10^5 steps. Convert the crate list once into a set of tuples so membership checks are O(1).
Hint 3
Keep the four directions in clockwise order, N, E, S, W. A right turn adds 1 to the index and a left turn subtracts 1, both modulo 4. For a backward step, negate the forward (dx, dy) vector. Compute the target cell first and only commit it if it is on the floor and not a crate.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a direct simulation. The rover's full state is (x, y, facing), and each instruction transforms that state in constant time.
- Crates in a hash set. There can be up to 10^5 crates and up to 10^5 step attempts. Scanning the list on each step could cost around 10^10 operations. Converting the crates once into a set of
(x, y)tuples makes each check O(1). The inner lists must be turned into tuples because lists are not hashable. - Facing as a circular index. Store the directions clockwise as
N, E, S, W. Turning right adds 1 to the index modulo 4, and turning left subtracts 1 modulo 4. Python's%returns a non-negative result, so(0 - 1) % 4 == 3, which correctly turnsNintoW. - Direction vectors. Each direction maps to a
(dx, dy)step. A backward step uses(-dx, -dy)and leaves the facing unchanged. - Validate, then commit. For
MorB, compute the target cell. Update(x, y)only if the target is on the floor and is not a crate. Otherwise the state stays as it was and the loop moves on. - No grid allocation. The floor can have up to 10^8 cells, so it is never materialized.
Why it is correct
Every instruction is a function of the current state only. Rotations change only the facing, and the circular order guarantees that L undoes R, and that four identical turns return to the original facing. Moves change only the position, and only when the target satisfies 0 <= nx < cols, 0 <= ny < rows, and is not a crate, which is exactly the rule in the statement. A rejected move leaves the state untouched and processing continues. Since the start is not a crate and the rover only ever enters legal cells, induction over the instruction string shows every intermediate state matches the specification, so the final state is correct.
Edge cases fall out naturally: an empty instruction string returns the start state, a 1x1 floor only allows rotations to have an effect, and duplicate crates collapse in the set.
Complexity
- Time: O(K + C), where K is the number of crates and C is the number of instructions.
- Space: O(K) for the crate set.
Reference solution
from typing import List
def run_rover(cols: int, rows: int, start: List[object], crates: List[List[int]], instructions: str) -> List[object]:
x, y, facing = start
blocked = {(cx, cy) for cx, cy in crates}
order = ['N', 'E', 'S', 'W']
vectors = {
'N': (0, 1),
'E': (1, 0),
'S': (0, -1),
'W': (-1, 0),
}
idx = order.index(facing)
for ch in instructions:
if ch == 'L':
idx = (idx - 1) % 4
elif ch == 'R':
idx = (idx + 1) % 4
else:
dx, dy = vectors[order[idx]]
if ch == 'B':
dx, dy = -dx, -dy
nx, ny = x + dx, y + dy
if 0 <= nx < cols and 0 <= ny < rows and (nx, ny) not in blocked:
x, y = nx, ny
return [x, y, order[idx]]