Approach
Breadth-first search
For 01 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
- 33 lines of Java from the credited upstream file 542-2.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 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[][] updateMatrix(int[][] mat) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = mat.length;5 final int n = mat[0].length;6 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();7 8 for (int i = 0; i < m; ++i)9 for (int j = 0; j < n; ++j)10 if (mat[i][j] == 0)11 q.offer(new Pair<>(i, j));12 else13 mat[i][j] = Integer.MAX_VALUE;14 15 while (!q.isEmpty()) {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 == m || y < 0 || y == n)22 continue;23 if (mat[x][y] <= mat[i][j] + 1)24 continue;25 q.offer(new Pair<>(x, y));26 mat[x][y] = mat[i][j] + 1;27 }28 }29 30 return mat;31 }32}33