Problem 570821 · medium · Phase 05 Advanced Algorithms & Graphs

Nearest Way Out of the Hedge Maze

grids · BFS · shortest path

A hedge maze is a list of equal-length strings maze: '.' is a path cell and '#' is hedge. You stand on the path cell start = [r, c]. Each step moves to a side-adjacent path cell. An exit is any path cell on the outer border of the grid other than the cell you start on.

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

Examples

Input:  maze = ["###.#",
                "#...#",
                "#.#.#",
                "#.###"], start = [2, 3]
Output: 2
Explanation: (2,3) -> (1,3) -> (0,3), which is on the top border.

Input:  same maze, start = [0, 3]
Output: 5
Explanation: the start does not count as an exit. The only other exit is (3,1):
(0,3) -> (1,3) -> (1,2) -> (1,1) -> (2,1) -> (3,1).

Input:  maze = ["."], start = [0, 0]
Output: -1

Constraints

  • 1 <= rows, cols <= 100; maze[start[0]][start[1]] == '.'
  • Target O(rows * cols) time.

Goals

  • Run a BFS whose target is a whole set of cells rather than one cell
  • Exclude the starting cell from the set of targets
Starting Python…