Tutorialspoint
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.
Hash MapAlgorithmsDeloitteGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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.

Steps to solve by this approach:

 Step 1: Convert the 2D board to a string representation for easier handling and hashing

 Step 2: Define the goal state based on the board dimensions
 Step 3: Use breadth-first search (BFS) to explore all possible moves from the initial state
 Step 4: For each state, find the position of the empty space (0) and try moving it in four directions
 Step 5: Track visited states to avoid cycles and return the minimum number of moves when the goal is reached

Submitted Code :