1. Problem Statement
On an 2 x 3 board, there are five tiles labeled from 1 to 5, and an empty square represented by 0. A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].
Given the puzzle board board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.
2. Approach: BFS on String States
This is finding the shortest path in an unweighted graph, where each "Node" is a specific configuration of the board.
- State Representation: A 2D matrix is hard to hash and store in a
visitedset. We serialize the 2x3 board into a 6-character string (e.g.,"123450"). - Target State:
"123450". - Transitions (Edges):
- The
0tile can swap with its neighbors. - Since we flattened a 2x3 grid to 1D, the neighbors of index
iare hardcoded:- 0 can swap with 1, 3
- 1 can swap with 0, 2, 4
- 2 can swap with 1, 5
- 3 can swap with 0, 4
- 4 can swap with 1, 3, 5
- 5 can swap with 2, 4
- The
- BFS: Push the initial string to a Queue. Generate all valid swaps, check if they equal the target, and push unseen states back to the Queue.
3. Java Implementation
public int slidingPuzzle(int[][] board) {
String target = "123450";
StringBuilder start = new StringBuilder();
for (int[] row : board) {
for (int val : row) {
start.append(val);
}
}
if (start.toString().equals(target)) return 0;
// Map 1D index to valid neighbor 1D indices
int[][] dirs = new int[][]{
{1, 3}, {0, 2, 4}, {1, 5},
{0, 4}, {1, 3, 5}, {2, 4}
};
Queue<String> q = new LinkedList<>();
Set<String> visited = new HashSet<>();
q.offer(start.toString());
visited.add(start.toString());
int moves = 0;
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
String curr = q.poll();
if (curr.equals(target)) return moves;
int zeroIndex = curr.indexOf('0');
for (int dir : dirs[zeroIndex]) {
String nextState = swap(curr, zeroIndex, dir);
if (!visited.contains(nextState)) {
visited.add(nextState);
q.offer(nextState);
}
}
}
moves++;
}
return -1;
}
private String swap(String str, int i, int j) {
char[] chars = str.toCharArray();
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
return new String(chars);
}
4. 5-Minute "Video-Style" Walkthrough
- The Graph Abstraction: There is no matrix traversal here. Think of
"412503"as Node A. Swapping0with5gives"412053", which is Node B. We are just running standard BFS from Node A to Node Target. - The Index Map: The
dirsarray is the secret weapon. It translates 2D adjacency into 1D arrays, completely eliminating the need for complexif (r > 0) ...bounds checking during the BFS loop. - The Serialization: Using Strings makes equality checks
curr.equals(target)andHashSetlookups incredibly fast and built-in to Java.
5. Interview Discussion
- Interviewer: "What is the time complexity?"
- You: "O(V + E). The number of vertices $V$ is the total possible states of a 2x3 board, which is $6! = 720$. For each state, we have at most 3 edges. So it's extremely fast and strictly bounded."
- Interviewer: "Can we use A* Search for this?"
- You: "Yes. For a 2x3 board, BFS is fast enough. If the board was 4x4 (15-puzzle), BFS would time out. We would need A* using the Manhattan Distance of each tile from its target position as the heuristic."