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 - BFS Approach INPUT Initial Board State: 1 2 3 4 0 5 Target State: 1 2 3 4 5 0 board = [[1,2,3],[4,0,5]] ALGORITHM STEPS 1 Convert to String "123405" for easy state comparison and hashing 2 BFS Queue Init Start with initial state Track visited states 3 Generate Neighbors Swap 0 with adjacent tiles (up/down/left/right) 4 Check Goal State If "123450" reached, return move count BFS State Exploration: 123405 123450 GOAL! FINAL RESULT Solution Found! Move 0: Initial 1 2 3 4 0 5 Swap Move 1: Solved! 1 2 3 4 5 0 Output: 1 Minimum moves = 1 Key Insight: BFS guarantees the shortest path in an unweighted graph. Each board state is a node, and valid moves are edges. Converting the 2D board to a string allows easy state tracking. The adjacency map defines which positions can swap with each index: {0:[1,3], 1:[0,2,4], 2:[1,5], 3:[0,4], 4:[1,3,5], 5:[2,4]} TutorialsPoint - Sliding Puzzle | BFS Approach
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