Approach
Breadth-first search
For Sliding Puzzle, 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
- 48 lines of Java from the credited upstream file 773.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 5 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 slidingPuzzle(int[][] board) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = 2;5 final int n = 3;6 final String goal = "123450";7 StringBuilder startSb = new StringBuilder();8 9 for (int i = 0; i < m; ++i)10 for (int j = 0; j < n; ++j)11 startSb.append((char) ('0' + board[i][j]));12 13 final String start = startSb.toString();14 if (start.equals(goal))15 return 0;16 17 Queue<String> q = new ArrayDeque<>(List.of(start));18 Set<String> seen = new HashSet<>(Arrays.asList(start));19 20 for (int step = 1; !q.isEmpty(); ++step)21 for (int sz = q.size(); sz > 0; --sz) {22 final String s = q.poll();23 final int zeroIndex = s.indexOf("0");24 final int i = zeroIndex / n;25 final int j = zeroIndex % n;26 for (int[] dir : DIRS) {27 final int x = i + dir[0];28 final int y = j + dir[1];29 if (x < 0 || x == m || y < 0 || y == n)30 continue;31 final int swappedIndex = x * n + y;32 StringBuilder sb = new StringBuilder(s);33 sb.setCharAt(zeroIndex, s.charAt(swappedIndex));34 sb.setCharAt(swappedIndex, s.charAt(zeroIndex));35 final String t = sb.toString();36 if (t.equals(goal))37 return step;38 if (!seen.contains(t)) {39 q.offer(t);40 seen.add(t);41 }42 }43 }44 45 return -1;46 }47}48