Approach
Breadth-first search
For The Maze II, 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
- 39 lines of Java from the credited upstream file 505.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 shortestDistance(int[][] maze, int[] start, int[] destination) {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 = new ArrayDeque<>(List.of(new Pair<>(start[0], start[1])));7 int[][] dist = new int[maze.length][maze[0].length];8 Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE));9 dist[start[0]][start[1]] = 0;10 11 while (!q.isEmpty()) {12 final int i = q.peek().getKey();13 final int j = q.poll().getValue();14 for (int[] dir : DIRS) {15 int x = i;16 int y = j;17 int step = dist[i][j];18 while (isValid(maze, x + dir[0], y + dir[1])) {19 x += dir[0];20 y += dir[1];21 ++step;22 }23 if (step < dist[x][y]) {24 dist[x][y] = step;25 q.offer(new Pair<>(x, y));26 }27 }28 }29 30 return dist[destination[0]][destination[1]] == Integer.MAX_VALUE31 ? -132 : dist[destination[0]][destination[1]];33 }34 35 private boolean isValid(int[][] maze, int x, int y) {36 return x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x][y] == 0;37 }38}39