
Problem
Solution
Submissions
Sliding Puzzle Problem
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
You are given an n x n board containing n² - 1 tiles and one empty space. The tiles are numbered from 1 to n² - 1. A move consists of sliding a tile horizontally or vertically into the empty space.
Example 1
- Input: board = [[1,2,3],[4,0,5],[7,8,6]]
- Output: 4
- Explanation:
- Step 1: The initial state is: 1 2 3 4 0 5 7 8 6
- Step 2: The goal state is: 1 2 3 4 5 6 7 8 0
- Step 3: We can solve this in 4 moves: - Move 5 down to get [[1,2,3],[4,8,0],[7,5,6]] - Move 8 right to get [[1,2,3],[4,0,8],[7,5,6]] - Move 4 down to get [[1,2,3],[0,4,8],[7,5,6]] - Move 1 right to get [[0,1,3],[2,4,8],[7,5,6]]
- Step 4: Therefore, the minimum number of moves required is 4.
Example 2
- Input: board = [[1,2,3],[4,5,0]]
- Output: 1
- Explanation:
- Step 1: The initial state is: 1 2 3 4 5 0
- Step 2: The goal state is: 1 2 3 4 5 0
- Step 3: Since the initial state is already the goal state, the answer is 0.
Constraints
- 2 ≤ n ≤ 4
- board.length == n
- board[i].length == n
- 0 ≤ board[i][j] ≤ n² - 1
- Each number in board appears exactly once.
- Time Complexity: O(n! * n²), where n is the board size.
- Space Complexity: O(n! * n²), where n is the board size.
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 to the solution.
- Represent the board state as a string for easy comparison and hashing.
- Generate all possible next states by moving the empty space in the four directions.
- Keep track of visited states to avoid cycles.
- Check if the puzzle is solvable before attempting to solve it.