On a 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 them.
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.
Function Signature
def sliding_puzzle(board: list[list[int]]) -> int:
Constraints
-
len(board) == 2
-
len(board[i]) == 3
-
0 <= board[i][j] <= 5
-
Each value
board[i][j]
is unique.
Examples
Input: board = [[1,2,3],[4,0,5]]
Output: 1
Swapping 0 and 5 reaches [[1,2,3],[4,5,0]] in one move.
Input: board = [[1,2,3],[5,4,0]]
Output: -1
No number of moves will make the board solved, so the answer is -1.
Input: board = [[4,1,2],[5,0,3]]
Output: 5
One shortest sequence moves 0 left, up, right, right and then down. Fewer moves cannot work: five tiles are each one square away from their solved position, and a move shifts only one tile by one square.