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

Steps to solve by this approach:

 Step 1: Convert the 2D board into a string representation for easier state management
 Step 2: Initialize BFS queue with the starting state and moves counter set to 0
 Step 3: Create an adjacency mapping for each position showing where tiles can move
 Step 4: For each state, find the position of the empty space (0)
 Step 5: Generate all possible next states by swapping 0 with adjacent tiles
 Step 6: Check if any new state matches the target; if so, return moves + 1
 Step 7: Add unvisited states to queue and continue BFS until solution found or queue empty

Submitted Code :