LeetCode 75

Nearest Exit from Entrance in Maze

Problem
LC 1926
Topic
Graph BFS
File
official75_LC1926NearestExitFromEntranceInMaze.java
Path
pkg5leetcode/official75/official75_LC1926NearestExitFromEntranceInMaze.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC1926NearestExitFromEntranceInMaze.java
Approach
BFS from entrance to border empty cell.
Complexity
Time O(mn), Space O(mn)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC1926NearestExitFromEntranceInMaze.java
1package pkg5leetcode.official75;2 3/*4 * Nearest Exit from Entrance in Maze | LC 19265 * APPROACH: BFS from entrance to border empty cell.6 * COMPLEXITY: Time O(mn), Space O(mn)7 */8import java.util.*;9 10public class official75_LC1926NearestExitFromEntranceInMaze {11    static int nearestExit(char[][] maze, int[] entrance) {12        int m = maze.length, n = maze[0].length;13        Deque<int[]> q = new ArrayDeque<>();14        q.add(new int[]{entrance[0], entrance[1], 0});15        maze[entrance[0]][entrance[1]] = '+';16        int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};17        while (!q.isEmpty()) {18            int[] cur = q.poll();19            for (int[] d : dirs) {20                int r = cur[0] + d[0], c = cur[1] + d[1], steps = cur[2] + 1;21                if (r < 0 || c < 0 || r >= m || c >= n || maze[r][c] == '+') continue;22                if ((r == 0 || c == 0 || r == m - 1 || c == n - 1) && steps > 0) return steps;23                maze[r][c] = '+';24                q.add(new int[]{r, c, steps});25            }26        }27        return -1;28    }29 30    public static void main(String[] args) {31        char[][] m1 = {{'+','+','.','+'},{'+','.','.','+'},{'+','+','+','.'}};32        check(nearestExit(m1, new int[]{1,2}) == 1, "case1");33        char[][] m2 = {{'.','+'}};34        check(nearestExit(m2, new int[]{0,0}) == -1, "case2");35        System.out.println("all tests passed");36    }37 38    static void check(boolean cond, String name) {39        if (!cond) throw new AssertionError("FAILED: " + name);40        System.out.println("  PASS " + name);41    }42}