1926. Nearest Exit from Entrance in Maze
Problem
In the maze, '.' is open and '+' is a wall. Starting at entrance, moving up, down, left or right, return the fewest steps to the nearest exit: an open cell on the border other than the entrance itself. Return −1 if none is reachable.
Example: maze = ["++.+","...+","+++."], entrance = [1,2] → 1
BFS from the entrance; the first border empty cell reached (other than the entrance itself) is the nearest exit.
Complexity: O(R·C).
class Solution:
def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
R, C = len(maze), len(maze[0])
start = tuple(entrance)
seen, q, steps = {start}, deque([start]), 0
while q:
steps += 1
for _ in range(len(q)):
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and maze[nr][nc] == "." and (nr, nc) not in seen:
if nr in (0, R - 1) or nc in (0, C - 1):
return steps
seen.add((nr, nc))
q.append((nr, nc))
return -1
G = lambda rows: [list(r) for r in rows]
assert Solution().nearestExit(G(["++.+", "...+", "+++."]), [1, 2]) == 1
assert Solution().nearestExit(G(["+++", "...", "+++"]), [1, 0]) == 2
assert Solution().nearestExit(G([".+"]), [0, 0]) == -1
class Solution {
public int nearestExit(char[][] maze, int[] entrance) {
int R = maze.length, C = maze[0].length;
boolean[][] seen = new boolean[R][C];
seen[entrance[0]][entrance[1]] = true;
Deque<int[]> q = new ArrayDeque<>(List.of(entrance));
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int steps = 1; !q.isEmpty(); steps++) {
for (int i = q.size(); i > 0; i--) {
int[] cur = q.poll();
for (int[] d : dirs) {
int r = cur[0] + d[0], c = cur[1] + d[1];
if (r < 0 || c < 0 || r >= R || c >= C || seen[r][c] || maze[r][c] != '.') continue;
if (r == 0 || c == 0 || r == R - 1 || c == C - 1) return steps;
seen[r][c] = true;
q.add(new int[]{r, c});
}
}
}
return -1;
}
}
func nearestExit(maze [][]byte, entrance []int) int {
R, C := len(maze), len(maze[0])
start := [2]int{entrance[0], entrance[1]}
seen, q := map[[2]int]bool{start: true}, [][2]int{start}
for steps := 1; len(q) > 0; steps++ {
next := [][2]int{}
for _, p := range q {
for _, d := range [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}} {
nr, nc := p[0]+d[0], p[1]+d[1]
if nr < 0 || nr >= R || nc < 0 || nc >= C || maze[nr][nc] != '.' || seen[[2]int{nr, nc}] {
continue
}
if nr == 0 || nr == R-1 || nc == 0 || nc == C-1 { // a border cell that is not the entrance
return steps
}
seen[[2]int{nr, nc}] = true
next = append(next, [2]int{nr, nc})
}
}
q = next
}
return -1
}