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 map is rows of characters: # is corn you cannot walk through, . is a path, S is the entrance and E the exit. Visitors move one square at a time, up, down, left or right.

The owner prints the fastest route's length on the ticket for visitors to beat. Some years a careless cut seals off the exit, 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), up to E at (1,3). 6 steps; nothing shorter gets 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, so the answer is -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 to E. (The first route depth-first search finds is often a long winding one.)

On an open 20 × 20 field that is hopeless. There are only 400 squares, but there is an astronomical number of simple paths, and most of them walk through squares that could have been reached faster another way.

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