This Python code implements the breadth-first search algorithm to solve the 8-puzzle problem. The goal is to rearrange a 3x3 grid of numbered tiles into a specific target state.
- Python 3.x
-
Clone the repository:
git clone https://github.com/collinblessing/8-puzzle-solver.git cd 8-puzzle-solver
-
Run the solver:
python main.py
The code defines a Node
class representing a node in the search tree. Each node contains information about its state, parent node, and the action that led to its creation.
-
breadth_first_search(initial_state, goal_state)
- Performs breadth-first search starting from the
initial_state
to reach thegoal_state
. - Uses a queue (
frontier
) to manage nodes to be explored and a set (explored
) to track visited states.
- Performs breadth-first search starting from the
-
get_successors(state)
- Generates successor states of a given
state
by moving the empty tile in different directions.
- Generates successor states of a given
-
reconstruct_path(node)
- Traces back the path from the goal state to the initial state by following parent nodes.
-
get_inversion_count(state)
- Calculates the inversion count of a given state, determining its solvability.
The code exhibits good cohesion, with each function having a clear and specific role in solving the 8-puzzle problem. The Node
class encapsulates relevant attributes, promoting cohesion within the codebase. The functions work cohesively to implement the breadth-first search algorithm.
Each function adheres to the Single Responsibility Principle, with a clear and singular purpose. However, to enhance code readability and maintainability, it is suggested to extract the inversion count check into a separate function.
This project is licensed under the MIT License - see the LICENSE file for details.