Shortest Route to an Exit with Fixed Direction Priority
Trees & GraphsAuto-graded · 19 test casesLast updated
Run BFS on a character grid to return the shortest move sequence to any exit, breaking ties by a fixed U, D, L, R direction priority.
Shortest Route to an Exit
You are given a rectangular map of a maze as a list of equal-length strings, and a starting cell. Find the sequence of moves that takes you from the start to the closest exit.
Map format
'#'is a wall and cannot be entered.'E'is an exit.- Every other character (for example
'.'or'S') is an open cell. startis a list[row, col]giving the starting cell.
Moves
| Move | Effect |
|---|---|
'U' | row decreases by 1 |
'D' | row increases by 1 |
'L' | column decreases by 1 |
'R' | column increases by 1 |
A move that would leave the grid is not allowed, exactly like a move into a wall.
Task
Implement shortest_exit_route(grid, start) so that it returns a list of move characters describing a route from start to some exit cell.
The route must follow these rules:
- It must use the minimum possible number of moves among all routes ending on any exit cell.
- If several routes have that minimum length, return the one that is smallest when compared move by move, using the priority
'U'<'D'<'L'<'R'. This is not alphabetical order. At the first position where two routes differ, the route whose move ranks higher in this priority is the better one. - If the starting cell is already an exit, return
[]. - If no exit can be reached from the start, return
[].
The maze may contain loops, dead ends, several exits, and regions that cannot be reached from the start.
Constraints
- The grid has at most 1,000 reachable open cells.
- All rows have the same length.
startis a valid in-bounds[row, col]position.- Only
'U','D','L','R'may appear in the returned list. - An empty grid yields
[].
Examples
Example 1
Input: shortest_exit_route(['#####', '#..##', '###E#', '#####'], [1, 1])
Output: []
Example 2
Input: shortest_exit_route(['E'], [0, 0])
Output: []
Example 3
Input: shortest_exit_route(['#######', '#.....#', '#.###.#', '#...E.#', '#######'], [1, 1])
Output: ['D', 'D', 'R', 'R', 'R']
Hints
Hint 1
Every move costs the same, so the shortest route is a breadth-first search problem. Keep a record of which cells you have already discovered so loops cannot trap you.
Hint 2
Store, for each discovered cell, the cell you came from and the move you used. When you reach an exit, walk those links back to the start and reverse the collected moves.
Hint 3
Tie-breaking comes for free if you always try neighbours in the fixed order U, D, L, R and mark a cell the first time it is discovered. Do not use alphabetical order, and do not reorder the directions.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each open cell as a graph node, with an edge between cells that are adjacent up, down, left or right. Every move has the same cost, so breadth-first search (BFS) finds shortest routes.
- If the start cell is an exit, return
[]immediately. - Put the start in a FIFO queue. Keep a dictionary
parentthat maps each discovered cell to the cell it was reached from. It doubles as the visited set. Keep a second dictionarymove_usedthat stores the move that first reached each cell. - Repeatedly pop a cell and examine its neighbours in the fixed order
U, D, L, R. Skip neighbours that are out of bounds, walls, or already discovered. - When a neighbour is discovered, record its parent and the move used. If it is an exit, follow the parent links back to the start, collecting moves, then reverse them and return.
- If the queue empties without finding an exit, return
[].
Why it is correct
Shortest length. BFS discovers cells in non-decreasing order of distance from the start, and a cell is recorded the first time it is discovered. So each recorded parent chain is a shortest route to that cell, and the first exit discovered is at minimum distance. Checking for an exit at discovery time is safe: all cells at distance k+1 are discovered while processing cells at distance k, so no closer exit can still be pending.
Tie-breaking. Use induction on BFS layers. Suppose the cells of layer k sit in the queue in lexicographic order of their recorded routes (under U < D < L < R), and each recorded route is the best shortest route to its cell. Layer k+1 is produced by scanning layer k in that order and trying directions in priority order, so its cells are discovered in order of (prefix, next move), which is the lexicographic order of the full route. A cell's first discovery therefore carries its best route, and the first exit found in a layer has the best route among all shortest routes to exits.
Termination. Each cell enters parent at most once, so loops cannot cause endless searching. Exits in unreachable regions are never visited, so [] is returned for them.
Complexity
- Time: O(R * C), since each cell is enqueued at most once and checks four neighbours.
- Space: O(R * C) for the queue,
parentandmove_used, plus the returned route.
Reference solution
from collections import deque
from typing import List
def shortest_exit_route(grid: List[str], start: List[int]) -> List[str]:
rows = len(grid)
if rows == 0:
return []
cols = len(grid[0])
sr, sc = start
if grid[sr][sc] == 'E':
return []
# The order of this list defines the tie-breaking priority U < D < L < R.
directions = [('U', -1, 0), ('D', 1, 0), ('L', 0, -1), ('R', 0, 1)]
queue = deque([(sr, sc)])
parent = {(sr, sc): None} # also acts as the visited set
move_used = {}
while queue:
r, c = queue.popleft()
for move, dr, dc in directions:
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
if grid[nr][nc] == '#' or (nr, nc) in parent:
continue
parent[(nr, nc)] = (r, c)
move_used[(nr, nc)] = move
if grid[nr][nc] == 'E':
path = []
cur = (nr, nc)
while cur != (sr, sc):
path.append(move_used[cur])
cur = parent[cur]
path.reverse()
return path
queue.append((nr, nc))
return []