
Problem
Solution
Submissions
Sliding Puzzle
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
You are given a 2x3 board with tiles numbered from 1 to 5 and one empty space represented by 0. The goal is to transform the board into [[1,2,3],[4,5,0]] by sliding tiles into the empty space. The board is represented as a 2D array where board[i][j] is the tile at position (i, j). Return the minimum number of moves required to solve the puzzle, or -1 if it's not solvable.
Example 1
- Input: board = [[1,2,3],[4,0,5]]
- Output: 1
- Explanation:
Step 1: The initial state is [[1,2,3],[4,0,5]].
Step 2: We can slide the 5 tile into the empty space: [[1,2,3],[4,5,0]].
Step 3: We have reached the target state with 1 move.
Example 2
- Input: board = [[4,1,2],[5,0,3]]
- Output: 5
- Explanation:
Step 1: The initial state is [[4,1,2],[5,0,3]].
Step 2: Through a series of optimal moves sliding tiles into the empty space
Step 3: We can reach the target state [[1,2,3],[4,5,0]] with a total of 5 moves.
Constraints
- board.length == 2
- board[i].length == 3
- 0 ≤ board[i][j] ≤ 5
- Each value board[i][j] is unique
- Time Complexity: O(6!)
- Space Complexity: O(6!)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use breadth-first search (BFS) to find the shortest path from the start state to the goal state.
- Represent each board state as a string for easy comparison and storing in visited set.
- For each state, generate all possible next states by moving the empty space in valid directions.
- Keep track of the number of moves made to reach each state.
- Use a visited set to avoid revisiting board configurations.