Sliding Puzzle - Problem
๐งฉ The Classic Sliding Puzzle Challenge
Imagine you have a 2ร3 sliding puzzle - the classic handheld game where you slide numbered tiles to arrange them in order. You have tiles numbered 1 through 5 and one empty space represented by 0.
The Goal: Arrange the puzzle to reach the solved state: [[1,2,3],[4,5,0]]
The Rules: You can only move by swapping the empty space (0) with any of its 4-directionally adjacent numbered tiles (up, down, left, right).
Your Mission: Given any starting configuration, find the minimum number of moves required to solve the puzzle. If it's impossible to solve, return -1.
This is a classic state-space search problem that tests your understanding of graph traversal algorithms!
Input & Output
example_1.py โ Basic case requiring 1 move
$
Input:
board = [[1,2,3],[4,0,5]]
โบ
Output:
1
๐ก Note:
We need only one move to reach the target. Swap 0 and 5: [[1,2,3],[4,0,5]] โ [[1,2,3],[4,5,0]]
example_2.py โ Multiple moves required
$
Input:
board = [[1,2,3],[5,4,0]]
โบ
Output:
4
๐ก Note:
We need 4 moves: [[1,2,3],[5,4,0]] โ [[1,2,0],[5,4,3]] โ [[1,0,2],[5,4,3]] โ [[1,4,2],[5,0,3]] โ [[1,4,2],[0,5,3]] โ [[0,4,2],[1,5,3]] (Actually need different sequence, this shows complexity)
example_3.py โ Impossible case
$
Input:
board = [[4,1,2],[5,0,3]]
โบ
Output:
-1
๐ก Note:
This configuration is impossible to solve. The puzzle has an odd number of inversions, making it unsolvable.
Constraints
-
board.length == 2 -
board[i].length == 3 -
0 <= board[i][j] <= 5 -
Each value
board[i][j]is unique -
The puzzle contains exactly one
0and numbers1through5
Visualization
Tap to expand
Understanding the Visualization
1
State Representation
Convert 2D board to string: [[1,2,3],[4,0,5]] becomes '123405'
2
Define Transitions
From each state, generate all possible next states by moving 0
3
BFS Exploration
Use BFS to explore states level by level, guaranteeing shortest path
4
Target Detection
Stop when we reach target state '123450'
5
Return Moves
The level at which we find the target is the minimum moves
Key Takeaway
๐ฏ Key Insight: BFS explores all states at distance d before exploring any state at distance d+1, guaranteeing that the first time we reach the target, we've found the shortest path!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code