KatInterview

Shortest Route to an Exit with Fixed Direction Priority

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsgridshortest-path

Last 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.
  • start is a list [row, col] giving the starting cell.

Moves

MoveEffect
'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:

  1. It must use the minimum possible number of moves among all routes ending on any exit cell.
  2. 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.
  3. If the starting cell is already an exit, return [].
  4. 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.
  • start is 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.