Shortest Looping Command Script for a Fuel-Limited Rover
Trees & GraphsAuto-graded · 17 test casesLast updated
Brute-force enumerate looping command scripts of length 1 to 10 and simulate each on a grid with fuel, walls and refuel pads, using state-repeat detection to stop loops.
A rover sits on a rectangular grid. You must find a short command script that, when repeated over and over, drives the rover into the rightmost column.
Grid
grid is a list of equal-length strings, one per row. Each character is one of:
.is an open cell.#is a wall.Fis a refuel pad (it is also an open cell the rover can enter).
start is [row, col], the rover's starting cell. It is not a wall and is not in the last column.
Rover and script
- The rover starts with 100 fuel units.
- A script is a string of length 1 to 10 over the letters
U,D,L,R,F. - The rover executes the script's commands in order. After the last command it returns to the first one, so the script loops indefinitely.
U,D,L,Rmove one cell up (row - 1), down (row + 1), left (col - 1) or right (col + 1), and cost 1 fuel.Frefuels. It is only allowed while the rover stands on a refuel pad, adds exactly 50 fuel, and does not move. There is no fuel cap, and a pad may be used any number of times.
When a script fails
A script fails as soon as any of these happens:
- A movement command would leave the grid or enter a wall.
- A movement command is issued while fuel is 0. Fuel is checked before the move, so a rover with 0 fuel cannot move, but it can still execute
Fon a pad. Fis executed on a cell that is not a refuel pad.- The rover never reaches the last column, i.e. it repeats forever. Equivalently, the same combination of (rover cell, position in the script) occurs a second time.
A script succeeds the moment the rover is in the last column. This is checked before executing each command.
Task
Return the script that succeeds and is chosen by this rule:
- Prefer the shortest script.
- Among scripts of the same length, take the one that is smallest in dictionary order using the letter order
U < D < L < R < F.
If no script of length 1 to 10 succeeds, return None.
Constraints
1 <= len(grid) <= 6,1 <= len(grid[0]) <= 8, and all rows have equal length.startis a valid, non-wall cell not in the last column.- Scripts have length between 1 and 10 inclusive.
- Output is a string of letters from
UDLRF, orNone.
Examples
Example 1
Input: find_rover_script(['...'], [0, 0])
Output: 'R'
Example 2
Input: find_rover_script(['.#.', '...'], [0, 0])
Output: 'DRR'
Example 3
Input: find_rover_script(['...', 'F##'], [1, 0])
Output: 'URR'
Hints
Hint 1
The number of candidate scripts is at most 5 + 5^2 + ... + 5^10, which is manageable if you generate them in length order and, within a length, in the required letter order, stopping at the first success.
Hint 2
To simulate one script, track (row, col, fuel, instruction index). Check for success before each command, and fail on any illegal move or illegal F.
Hint 3
A script can loop forever. Remember each (row, col, instruction index) seen; seeing one again means the rover is in a cycle that never reaches the last column, so the script fails.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The search space is small enough to enumerate completely. There are 5 letters and lengths 1 to 10, so at most about 12 million scripts. In practice the search stops far earlier.
- Generate scripts by increasing length. Within one length, use
itertools.product('UDLRF', repeat=length), which yields tuples in dictionary order for the given alphabet orderU < D < L < R < F. The first script that succeeds is therefore exactly the one the tie-break rule asks for. - For each script, simulate the rover:
- Keep
(row, col, fuel, ip). - Before each command, if the column is the last one, succeed.
- If the pair (cell, instruction index) was visited before, fail.
- For
F, require a pad and add 50 fuel. For a move, require fuel > 0, an in-grid target and a non-wall target, then move and spend 1 fuel. - Advance
ipmodulo the script length.
- Keep
- If no script of length 1 to 10 works, return
None.
Why it is correct
- Enumeration order gives shortest-first, then lexicographic, so the first success is the required answer, and
Noneis returned only after every script was rejected. - Termination: the rover's future behaviour depends only on its cell and instruction index, except that fuel can cause a failure. If a (cell, index) pair repeats, the rover is in a cycle. It either runs out of fuel in that cycle or stays in it forever, and neither reaches the last column (success is checked at every step, so it would have already succeeded). Declaring failure is therefore right. The number of distinct states is at most
rows * cols * len(script), so each simulation is bounded.
Complexity
- Time:
O(5^10 * R * C * 10)in the worst case, since there are up to about5^10scripts and each simulation visits at mostR * C * Lstates. Early exit makes typical inputs much faster. - Space:
O(R * C * L)for the visited set of one simulation, plus the current script.
Reference solution
from itertools import product
from typing import List, Optional
def find_rover_script(grid: List[str], start: List[int]) -> Optional[str]:
rows, cols = len(grid), len(grid[0])
sr, sc = start
deltas = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
def works(script: str) -> bool:
r, c, fuel, ip = sr, sc, 100, 0
seen = set()
while True:
if c == cols - 1:
return True
state = (r, c, ip)
if state in seen:
return False
seen.add(state)
cmd = script[ip]
if cmd == 'F':
if grid[r][c] != 'F':
return False
fuel += 50
else:
if fuel == 0:
return False
dr, dc = deltas[cmd]
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr][nc] == '#':
return False
r, c = nr, nc
fuel -= 1
ip = (ip + 1) % len(script)
for length in range(1, 11):
for letters in product('UDLRF', repeat=length):
script = ''.join(letters)
if works(script):
return script
return None