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.
Input: board =[[4,1,2],[5,0,3]]Output: 5Explanation: 5is the smallest number of moves that solves the board.An example path:After move 0:[[4,1,2],[5,0,3]]After move 1:[[4,1,2],[0,5,3]]After move 2:[[0,1,2],[4,5,3]]After move 3:[[1,0,2],[4,5,3]]After move 4:[[1,2,0],[4,5,3]]After move 5:[[1,2,3],[4,5,0]]
To solve this problem, we can use the Breadth-First Search (BFS) approach, which is suitable for finding the shortest path in an unweighted graph. Below are the steps:
Convert Board to String: Transform the 2x3 board into a string to make it easier to handle states and transitions.
Initialisations: Use a queue to perform BFS and a set to keep track of visited states.
BFS Implementation:
Dequeue the current state and explore all possible moves by swapping the blank tile (0) with its 4-directionally adjacent tiles.
For each move, if the new state equals the goal state, return the depth (number of moves).
Otherwise, enqueue the new state if it hasn’t been visited.
Goal Check: If the queue is empty and the goal state hasn’t been reached, return -1.
⏰ Time complexity: O((n*m)!) where n*m is the size of the board (2x3 in this case), due to the fact that this problem is equivalent to solving a permutation problem.
🧺 Space complexity: O((n*m)!) for queue and set to store all possible states.