AlgoFrames

Nearest exit in a maze

Standard · Write code · about 12 min

A maze is a grid where 0 is an open cell and 1 is a wall. You start at entrance, given as [row, col], and each step moves one cell up, down, left or right onto an open cell.

An exit is an open cell on the border of the grid other than the entrance. Return the fewest steps to the nearest exit, or -1 if there is none.

Example 1

Input:

[[[1,1,1,1,1],[1,0,0,0,0],[1,0,1,1,1],[0,0,0,0,1],[1,1,1,1,1]],[3,0]]

Output:

6

Right 1, up 2, right 3 reaches the exit at row 1, column 4 in 6 steps.

Example 2

Input:

[[[0,1],[1,0]],[0,0]]

Output:

-1

The only other open cell touches the entrance only at a corner.

Constraints

  • 1 ≤ rows, cols ≤ 100
  • grid[r][c] is 0 or 1
  • entrance is an open cell
  • Moves are up, down, left, right; no diagonals

Learn the idea first: Shortest paths in unweighted graphs; path reconstruction, a visual lesson.

More Shortest paths in unweighted graphs; path reconstruction problems