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 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, 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 & Output

Example 1 — Basic Case
$ Input: board = [[1,2,3],[4,0,5]]
Output: 1
💡 Note: Swap the 0 and the 5 in one move: [[1,2,3],[4,0,5]] → [[1,2,3],[4,5,0]]
Example 2 — Multiple Moves
$ Input: board = [[1,2,3],[5,4,0]]
Output: -1
💡 Note: No number of moves will make the board solved. The puzzle is unsolvable.
Example 3 — Already Solved
$ Input: board = [[1,2,3],[4,5,0]]
Output: 0
💡 Note: The board is already in the solved state, so 0 moves are needed.

Constraints

  • board.length == 2
  • board[i].length == 3
  • 0 ≤ board[i][j] ≤ 5
  • Each value board[i][j] is unique

Visualization

Tap to expand
Sliding Puzzle: Find Minimum Moves to Target123405Initial: [[1,2,3],[4,0,5]]1 moveSwap 0↔5123450Target: [[1,2,3],[4,5,0]]BFS AlgorithmExplores states level by levelOutput: 1 (minimum moves needed)
Understanding the Visualization
1
Input
2x3 board with tiles 1-5 and empty space 0
2
Process
Move empty space to adjacent positions
3
Output
Minimum moves to reach [[1,2,3],[4,5,0]]
Key Takeaway
🎯 Key Insight: Model as graph problem where each board state is a node and find shortest path using BFS
Asked in
Google 15 Facebook 12 Amazon 8
89.0K Views
Medium Frequency
~25 min Avg. Time
2.3K 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