
Problem
Solution
Submissions
Sliding Puzzle
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to solve a sliding puzzle. The puzzle consists of a 2x3 board with tiles numbered from 1 to 5 and one empty space represented by 0. The goal is to arrange the tiles to match the target configuration [[1,2,3],[4,5,0]] using the minimum number of moves. You can slide a tile into the empty space if they are adjacent (horizontally or vertically).
Example 1
- Input: board = [[1,2,3],[4,0,5]]
- Output: 1
- Explanation:
- Initial board: [[1,2,3],[4,0,5]].
- Target board: [[1,2,3],[4,5,0]].
- Move tile 5 left to position of 0: [[1,2,3],[4,5,0]].
- One move is sufficient to solve the puzzle.
- Initial board: [[1,2,3],[4,0,5]].
Example 2
- Input: board = [[1,2,3],[5,4,0]]
- Output: -1
- Explanation:
- Initial board: [[1,2,3],[5,4,0]].
- Target board: [[1,2,3],[4,5,0]].
- This configuration is not solvable.
- Return -1 as it's impossible to reach the target.
- Initial board: [[1,2,3],[5,4,0]].
Constraints
- board.length == 2
- board[i].length == 3
- 0 ≤ board[i][j] ≤ 5
- Each number from 0 to 5 appears exactly once
- 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 BFS to find the minimum number of moves
- Convert the 2D board to a string for easy state comparison
- For each state, find the position of 0 (empty space)
- Generate all possible next states by swapping 0 with adjacent tiles
- Use a visited set to avoid revisiting the same state
- Return the number of moves when target state is reached