Corn Maze Shortcut

Easybreadth-first searchAlso known as Shortest Path in a Maze

A farm cuts a maze into its corn field every autumn. The owner has the map as rows of characters: # is corn you cannot walk through, . is a path, S is the entrance and E is the exit. Visitors move one square at a time, up, down, left or right.

The owner wants to print the length of the fastest route on the ticket, so visitors know what to beat. Some years a careless cut leaves the exit sealed off, and the ticket should say so.

Your task

Write shortestWalk(maze). maze is a list of equal-length strings. Return the smallest number of steps to get from S to E, where each step moves to a neighboring square up, down, left or right that is not #.

Return -1 if there is no way to reach E. You cannot step outside the map.

shortestWalk(maze: string[]) → int

Examples

Example 1
Input
maze = ["S.#.", "..#E", "#...", "...."]
Output
6
Why

The wall in column 2 blocks the top two rows. One fastest route: down to (1,0), right to (1,1), down to (2,1), right to (2,2) and (2,3), then up to E at (1,3). That is 6 steps, and no route is shorter because you must go around the wall.

Example 2
Input
maze = ["S#E"]
Output
-1
Why

The only square between S and E is corn, and there is nowhere else to go. Return -1.

Constraints

  • 1 ≤ rows, cols ≤ 20
  • Each character is '#', '.', 'S' or 'E'
  • There is exactly one 'S' and exactly one 'E'
Start with brute force

Try every route with a depth-first search: walk from S, try each direction, back up at dead ends, and keep the shortest route that reaches E. Do not just return the first route found: depth-first search finds a route, often a long winding one.

Trying every route is hopeless on an open 20 × 20 field. The number of different simple paths across it is astronomically large, even though there are only 400 squares. Most of that work re-walks squares you could already reach faster.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code