๐Ÿงฉ 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 0 and numbers 1 through 5

Visualization

Tap to expand
1 2 34 0 5Start State1 2 30 4 51 2 34 5 0TARGET!1 0 34 2 5โœ“BFS Process:1. Start with initial state2. Generate all possible moves (neighbors)3. Add unvisited states to queue4. First time we see target = minimum moves!Answer: 1 moveBFS guarantees optimal solution
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!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 25
78.5K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen