Tutorialspoint
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!)
ArraysAlgorithmsTech MahindraWalmart
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 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.

Steps to solve by this approach:

 Step 1: Convert the 2D board into a 1D string representation for easier manipulation and state comparison.
 Step 2: Define the target state "123450" that represents the solved puzzle.
 Step 3: Create a mapping of all possible moves for each position where the empty space (0) can be.
 Step 4: Use BFS to explore all possible board states, starting from the initial state.
 Step 5: For each state, check if it matches the target state. If yes, return the current number of moves.
 Step 6: Generate all next possible states by swapping the empty space with adjacent positions.
 Step 7: Keep track of visited states to avoid cycles and optimize search.

Submitted Code :