All problems
1036MediumArrayBreadth-First SearchMatrix

The Nearest Way Out of the Vault

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1926Nearest Exit from Entrance in Maze

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A vault floor is given as the grid vault, where '.' marks an open cell and '+' marks a wall. A step moves to a cell sharing an edge with the current one, and only open cells may be stood on.

You start on the open cell at row start[0] and column start[1]. An exit is any open cell on the outer edge of the grid other than the cell you start on.

Return the fewest steps needed to reach an exit, or -1 when no exit can be reached.

Examples

Example 1

Input
vault = [[".", ".", "."], [".", "+", "."], [".", ".", "."]], start = [1, 0]
Output
1

The starting cell sits on the left edge, but it cannot count as its own exit. The cell straight above it is open and also on the edge, so one step is enough.

Example 2

Input
vault = [["+", "+", "+"], ["+", ".", "+"], ["+", "+", "+"]], start = [1, 1]
Output
-1

The only open cell is walled in on all four sides, so no exit can be reached.

Example 3

Input
vault = [["+", "+", "+", "+", "+"], ["+", ".", ".", ".", "."], ["+", ".", "+", "+", "+"], ["+", ".", "+", "+", "+"], ["+", ".", "+", "+", "+"]], start = [1, 1]
Output
3

Two exits are reachable: the open cell at the right end of the second row and the one at the bottom of the second column. Both lie three steps away.

Constraints

  • 1 <= vault.length <= 100
  • 1 <= vault[i].length <= 100
  • Every cell of vault is a full stop or a plus sign.
  • start.length == 2
  • 0 <= start[0] <= vault.length - 1
  • The cell you start on is open.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def nearest_exit(vault: list[list[str]], start: list[int]) -> int:
Java
public int nearestExit(char[][] vault, int[] start)
September 7
Apply