Program to find number of steps to solve 8-puzzle in python

The 8-puzzle is a classic sliding puzzle game where you have a 3x3 grid with numbers 0-8, and you need to arrange them in order by sliding tiles into the empty space (represented by 0). This problem asks us to find the minimum number of steps to solve the puzzle using a breadth-first search approach.

Understanding the Problem

Given a 3x3 board with numbers 0-8 (no duplicates), we can swap the 0 with any of its adjacent neighbors. The goal is to arrange the numbers in sequential order from 0 to 8.

For example, if we have this initial state:

3 1 2
4 7 5
6 8 0

The target state should be:

0 1 2
3 4 5
6 7 8

Solution Approach

We use Breadth-First Search (BFS) to find the minimum number of steps. The algorithm explores all possible moves level by level until it reaches the target configuration.

Key Components

The solution consists of three main methods:

  • find_next() - Generates all possible next states from current state
  • get_paths() - Performs BFS to find minimum steps
  • solve() - Main method that coordinates the solution

Implementation

class Solution:
    def solve(self, board):
        visited = {}
        flatten = []
        
        # Convert 2D board to 1D tuple for easier processing
        for i in range(len(board)):
            flatten += board[i]
        flatten = tuple(flatten)
        
        visited[flatten] = 0
        
        # Check if already solved
        if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
            return 0
        
        return self.get_paths(visited)
    
    def get_paths(self, visited):
        steps = 0
        
        while True:
            # Get all nodes at current step level
            current_nodes = [state for state in visited if visited[state] == steps]
            
            if len(current_nodes) == 0:
                return -1  # No solution found
            
            for node in current_nodes:
                next_moves = self.find_next(node)
                
                for move in next_moves:
                    if move not in visited:
                        visited[move] = steps + 1
                        
                        # Check if we reached the target
                        if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
                            return steps + 1
            
            steps += 1
    
    def find_next(self, node):
        # Define possible moves for each position (0-8)
        moves = {
            0: [1, 3],           # Top-left corner
            1: [0, 2, 4],        # Top-middle
            2: [1, 5],           # Top-right corner
            3: [0, 4, 6],        # Middle-left
            4: [1, 3, 5, 7],     # Center (can move in all 4 directions)
            5: [2, 4, 8],        # Middle-right
            6: [3, 7],           # Bottom-left corner
            7: [4, 6, 8],        # Bottom-middle
            8: [5, 7],           # Bottom-right corner
        }
        
        results = []
        pos_0 = node.index(0)  # Find position of empty space
        
        # Generate all possible moves
        for move_pos in moves[pos_0]:
            new_node = list(node)
            # Swap 0 with adjacent number
            new_node[move_pos], new_node[pos_0] = new_node[pos_0], new_node[move_pos]
            results.append(tuple(new_node))
        
        return results

# Test the solution
ob = Solution()
matrix = [
    [3, 1, 2],
    [4, 7, 5],
    [6, 8, 0]
]
print("Minimum steps required:", ob.solve(matrix))

Output

Minimum steps required: 4

How It Works

The algorithm works as follows:

  1. Initialization: Convert the 2D board to a 1D tuple for easier manipulation
  2. BFS Traversal: Explore all possible states level by level
  3. State Generation: For each state, generate all valid moves by swapping 0 with adjacent numbers
  4. Target Check: Stop when we reach the target configuration (0,1,2,3,4,5,6,7,8)
  5. Step Counting: Return the minimum number of steps required

Time and Space Complexity

The time complexity is O(9!) in the worst case, as there are 9! possible configurations of the puzzle. The space complexity is also O(9!) for storing visited states in the dictionary.

Conclusion

This BFS-based solution efficiently finds the minimum number of steps to solve an 8-puzzle by exploring all possible moves systematically. The algorithm guarantees finding the optimal solution due to the breadth-first nature of the search.

Updated on: 2026-03-25T13:02:20+05:30

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements