Approach
Breadth-first search
For Nearest Exit from Entrance in Maze, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 32 lines of Java from the credited upstream file 1926.java.
- The implementation visibly relies on sequence storage, work queue.
- 3 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int nearestExit(char[][] maze, int[] entrance) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = maze.length;5 final int n = maze[0].length;6 Queue<Pair<Integer, Integer>> q =7 new ArrayDeque<>(List.of(new Pair<>(entrance[0], entrance[1])));8 boolean[][] seen = new boolean[m][n];9 seen[entrance[0]][entrance[1]] = true;10 11 for (int step = 1; !q.isEmpty(); ++step)12 for (int sz = q.size(); sz > 0; --sz) {13 final int i = q.peek().getKey();14 final int j = q.poll().getValue();15 for (int[] dir : DIRS) {16 final int x = i + dir[0];17 final int y = j + dir[1];18 if (x < 0 || x == m || y < 0 || y == n)19 continue;20 if (seen[x][y] || maze[x][y] == '+')21 continue;22 if (x == 0 || x == m - 1 || y == 0 || y == n - 1)23 return step;24 q.offer(new Pair<>(x, y));25 seen[x][y] = true;26 }27 }28 29 return -1;30 }31}32