Problem Description
Given a 2x3 board with tiles labeled 1 through 5 and an empty square represented by 0, the goal is to move the board from its initial state to the solved state [[1,2,3],[4,5,0]] by sliding the 0 tile with one of its 4-directionally adjacent numbers. Return the minimum number of moves required to solve the board. If the board is unsolvable, return -1.
Key Insights
- Represent the board as a string (e.g. "123450") to simplify state comparison and manipulation.
- Use Breadth First Search (BFS) to explore all possible moves since the puzzle has a small fixed state space (6! = 720 possible states).
- Precompute the valid neighbor indices for each board position to efficiently generate new states.
- Track visited states to avoid loops and redundant work.
Space and Time Complexity
Time Complexity: O(1) in practice, since there are at most 720 states (6! permutations). Space Complexity: O(1) for the same reason, as the state space is fixed and limited.
Solution
We solve the problem using a Breadth First Search (BFS) approach. The board configuration is flattened into a string to represent states. A mapping from each index to its possible neighbors (i.e., positions to which 0 can move) is precomputed. BFS is then used to explore every valid move from the initial state while marking states as visited to avoid cycles. When the goal state ("123450") is reached, we return the number of moves taken. If BFS completes without reaching the goal, the puzzle is unsolvable and we return -1.