BFS over states
Time O(6! × 3) Space O(6!)Level-order BFS from the start string; neighbours swap '0' with adjacent indices.
import java.util.*;
class Solution {
private static final int[][] NEXT = {{1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4}};
public int slidingPuzzle(int[][] board) {
StringBuilder sb = new StringBuilder();
for (int[] row : board) for (int x : row) sb.append(x);
String start = sb.toString(), target = "123450";
Set<String> seen = new HashSet<>(List.of(start));
Deque<String> q = new ArrayDeque<>(List.of(start));
for (int moves = 0; !q.isEmpty(); moves++) {
for (int size = q.size(); size > 0; size--) {
String s = q.poll();
if (s.equals(target)) return moves;
int z = s.indexOf('0');
for (int j : NEXT[z]) {
char[] c = s.toCharArray();
c[z] = c[j];
c[j] = '0';
String t = new String(c);
if (seen.add(t)) q.offer(t);
}
}
}
return -1;
}
}Verdict: Only 720 states.