660. Nearest Maze Exit

Medium3.5 points estimatedMatrixGraphBreadth-First Search3 hints

A visitor enters a rectangular hedge maze through the cell given by entrance, written as [row, column]. Cells marked '.' are open paths and cells marked '#' are hedges. In one step the visitor moves to an open cell directly above, below, left or right. If the entrance cell is itself a hedge, there is no walk at all and the answer is -1.

An exit is any open cell on the outer edge of the maze (first or last row, first or last column) other than the entrance cell itself. Return the smallest number of steps from the entrance to the nearest exit, or -1 if no exit can be reached. The entrance does not count as an exit even when it lies on the edge. Aim for O(R * C) time and O(R * C) space.

Example 1

Input:
maze = [["#","#","#",".","#"],["#",".",".",".","#"],["#",".","#",".","#"],["#",".",".",".","#"],["#","#",".","#","#"]]entrance = [3,1]
Output:
2
Explanation:

From the entrance at (3,1) the closest border opening is at (4,2), reached in 2 steps.

Example 2

Input:
maze = [["#","#","#","#","#"],["#",".",".",".","#"],["#","#","#","#","#"]]entrance = [1,2]
Output:
-1
Explanation:

The corridor is sealed on every border cell, so no exit exists and the answer is -1.

Example 3

Input:
maze = [[".",".",".",".","."],["#","#","#","#","#"],[".",".",".",".","."]]entrance = [0,0]
Output:
1
Explanation:

Starting at (0,0) the walker can only move along the top row. The nearest other border cell is next door, so the answer is 1.

Constraints

1 ≤ R, C ≤ 300

maze[i][j] is '.' or '#'

entrance has two values: 0 ≤ entrance[0] < R and 0 ≤ entrance[1] < C

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(R * C)
Space
O(R * C)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…