Approach
Breadth-first search
For Matrix Cells in Distance Order, 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
- 28 lines of Java from the credited upstream file 1030.java.
- The implementation visibly relies on sequence storage, work queue.
- 2 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[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 List<int[]> ans = new ArrayList<>();5 boolean[][] seen = new boolean[rows][cols];6 Queue<Pair<Integer, Integer>> q = new LinkedList<>(Arrays.asList(new Pair<>(rCenter, cCenter)));7 seen[rCenter][cCenter] = true;8 9 while (!q.isEmpty()) {10 final int i = q.peek().getKey();11 final int j = q.poll().getValue();12 ans.add(new int[] {i, j});13 for (int[] dir : DIRS) {14 final int x = i + dir[0];15 final int y = j + dir[1];16 if (x < 0 || x == rows || y < 0 || y == cols)17 continue;18 if (seen[x][y])19 continue;20 seen[x][y] = true;21 q.offer(new Pair<>(x, y));22 }23 }24 25 return ans.toArray(int[][] ::new);26 }27}28