Approach
Breadth-first search
For Shortest Path in Binary Matrix, 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
- 35 lines of Java from the credited upstream file 1091.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 shortestPathBinaryMatrix(int[][] grid) {3 final int n = grid.length;4 if (grid[0][0] == 0 && n == 1)5 return 1;6 if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1)7 return -1;8 9 final int[][] DIRS = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};10 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(0, 0)));11 boolean[][] seen = new boolean[n][n];12 seen[0][0] = true;13 14 for (int step = 1; !q.isEmpty(); ++step)15 for (int sz = q.size(); sz > 0; --sz) {16 final int i = q.peek().getKey();17 final int j = q.poll().getValue();18 for (int[] dir : DIRS) {19 final int x = i + dir[0];20 final int y = j + dir[1];21 if (x < 0 || x == n || y < 0 || y == n)22 continue;23 if (grid[x][y] != 0 || seen[x][y])24 continue;25 if (x == n - 1 && y == n - 1)26 return step + 1;27 q.offer(new Pair<>(x, y));28 seen[x][y] = true;29 }30 }31 32 return -1;33 }34}35