• Branch and Bound Tutorial
  • Backtracking Vs Branch-N-Bound
  • 0/1 Knapsack
  • 8 Puzzle Problem
  • Job Assignment Problem
  • N-Queen Problem
  • Travelling Salesman Problem
  • Branch and Bound Algorithm
  • Introduction to Branch and Bound - Data Structures and Algorithms Tutorial
  • 0/1 Knapsack using Branch and Bound
  • Implementation of 0/1 Knapsack using Branch and Bound

8 puzzle Problem using Branch And Bound

  • Job Assignment Problem using Branch And Bound
  • N Queen Problem using Branch And Bound
  • Traveling Salesman Problem using Branch And Bound

We have introduced Branch and Bound and discussed the 0/1 Knapsack problem in the below posts. 

  • Branch and Bound | Set 1 (Introduction with 0/1 Knapsack)
  • Branch and Bound | Set 2 (Implementation of 0/1 Knapsack)

In this puzzle solution of the 8 puzzle problem is discussed.  Given a 3×3 board with 8 tiles (every tile has one number from 1 to 8) and one empty space. The objective is to place the numbers on tiles to match the final configuration using the empty space. We can slide four adjacent (left, right, above , and below) tiles into the empty space. 

For example, 

8puzzle

1. DFS (Brute-Force)   We can perform a depth-first search on state-space (Set of all configurations of a given problem i.e. all states that can be reached from the initial state) tree.   

image(6)

In this solution, successive moves can take us away from the goal rather than bringing us closer. The search of state-space tree follows the leftmost path from the root regardless of the initial state. An answer node may never be found in this approach.

2. BFS (Brute-Force)   We can perform a Breadth-first search on the state space tree. This always finds a goal state nearest to the root. But no matter what the initial state is, the algorithm attempts the same sequence of moves like DFS.

3. Branch and Bound   The search for an answer node can often be speeded by using an “intelligent” ranking function, also called an approximate cost function to avoid searching in sub-trees that do not contain an answer node. It is similar to the backtracking technique but uses a BFS-like search.

There are basically three types of nodes involved in Branch and Bound  1. Live node is a node that has been generated but whose children have not yet been generated.  2. E-node is a live node whose children are currently being explored. In other words, an E-node is a node currently being expanded.  3. Dead node is a generated node that is not to be expanded or explored any further. All children of a dead node have already been expanded.

Cost function:  Each node X in the search tree is associated with a cost. The cost function is useful for determining the next E-node. The next E-node is the one with the least cost. The cost function is defined as 

The ideal Cost function for an 8-puzzle Algorithm :  We assume that moving one tile in any direction will have a 1 unit cost. Keeping that in mind, we define a cost function for the 8-puzzle algorithm as below: 

An algorithm is available for getting an approximation of h(x) which is an unknown value.

Complete Algorithm:  

The below diagram shows the path followed by the above algorithm to reach the final configuration from the given initial configuration of the 8-Puzzle. Note that only nodes having the least value of cost function are expanded.  

explain problem solving agent of 8 puzzle problem

Output : 

The time complexity of this algorithm is O(N^2 * N!) where N is the number of tiles in the puzzle, and the space complexity is O(N^2) .

Sources:   www.cs.umsl.edu/~sanjiv/classes/cs5130/lectures/bb.pdf   https://www.seas.gwu.edu/~bell/csci212/Branch_and_Bound.pdf

Please Login to comment...

Similar reads.

  • Branch and Bound
  • Otter.ai vs. Fireflies.ai: Which AI Transcribes Meetings More Accurately?
  • Google Chrome Will Soon Let You Talk to Gemini In The Address Bar
  • AI Interior Designer vs. Virtual Home Decorator: Which AI Can Transform Your Home Into a Pinterest Dream Faster?
  • Top 10 Free Webclipper on Chrome Browser in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

CodingDrills logo

The Eight Puzzle Problem

Recursion algorithms: backtracking and recursion - the eight puzzle problem.

Recursion is a powerful technique used in programming for solving complex problems by breaking them down into smaller, more manageable subproblems. In this tutorial, we will explore the fascinating world of recursion algorithms, with a specific focus on backtracking and recursion in relation to the Eight Puzzle Problem.

Understanding Recursion and Backtracking

Recursion is a process where a function calls itself directly or indirectly. It involves breaking down a problem into smaller subproblems of the same type, solving each subproblem independently, and then combining the solutions to obtain the final solution.

Backtracking, on the other hand, is a specific technique used in recursion algorithms to efficiently explore all possible solutions by trying out different options and undoing (backtracking) whenever we reach an undesirable state.

The Eight Puzzle, also known as the sliding tile puzzle, is a classic problem that involves a 3x3 grid with eight numbered tiles and an empty cell. The goal is to rearrange the tiles to reach a desired configuration, typically ordered from 1 to 8, with the empty cell in a specific position.

To solve the Eight Puzzle Problem using recursion and backtracking, we can represent the problem state as a matrix and apply a depth-first search algorithm.

Let's take a look at a simple implementation of the Eight Puzzle Problem using Python:

In the above code snippet, we define a class EightPuzzle that represents the problem. It has various methods such as solve , get_neighbors , is_goal_state , print_solution , and run to perform the necessary operations.

Implementing the Solver

To solve the Eight Puzzle Problem, we need to implement the solving logic within the solve method. This is where we apply backtracking and recursion to explore all possible states until we reach the goal state.

Here's a high-level overview of the solving logic:

Check if the initial state is already the goal state. If so, we can terminate the recursion and print the solution.

If the initial state is not the goal state, generate all possible neighboring states using the get_neighbors method.

Iterate through each neighboring state and recursively call the solve method with the new state as the input.

If the solving logic returns True , it means the goal state has been reached. We can terminate the recursion and print the solution.

If none of the neighboring states lead to the goal state, we perform backtracking by undoing the last move and exploring the next neighbor.

By implementing this recursive backtracking approach, we can efficiently solve the Eight Puzzle Problem and find the optimal path to reach the desired configuration.

Handling Constraints and Optimizations

When implementing recursion algorithms, it's essential to consider constraints and optimize the code for better performance.

For example, in the case of the Eight Puzzle Problem, we can incorporate heuristics like the Manhattan distance to prioritize exploring states that are more likely to lead to the goal state. This helps reduce the number of unnecessary recursive calls, improving the overall efficiency of the solution.

Recursion and backtracking provide a powerful approach to solving complex problems like the Eight Puzzle Problem. By breaking down the problem into smaller subproblems and efficiently exploring all possible solutions, we can find optimal solutions and gain a deeper understanding of these fundamental programming concepts.

In this tutorial, we explored the basics of recursion and backtracking, and implemented a simple solver for the Eight Puzzle Problem. Leveraging code snippets, examples, and high-level explanations, we aimed to provide a comprehensive understanding of these concepts for programmers.

Now it's your turn to take this knowledge and apply it to solve other challenging problems using the power of recursion and backtracking!

Happy coding!

CodingDrills logo

Hi, I'm Ada, your personal AI tutor. I can help you with any coding tutorial. Go ahead and ask me anything.

I have a question about this topic

Give more examples

A sliding block puzzle, whose solution is found using A* Search.

author : sasank mail-id : [email protected] last mod. : 03/01/2017

Note : The distinction between a state and a node is crucial to the understanding of A* Search, which is used to solve the 8Puzzle problem. However, the terms node & state are used interchangebly in this document. In fact, this distinction is important to understand any AI search algorithm.

a. Problem Definition :

In this puzzle, we have a 3x3 grid containing 9 squares containing 8 tiles and 1 blank. The 8 tiles are numbered 1 to 8. The blank can move up, down, left or right depending on it’s position.

Given an arbitrary initial configuration of the grid, the problem solving agent needs to find an optimal sequence of actions that lead to the goal state, if there is one.

The intial state can be any possible configuration of the 3x3 grid. On the other hand, the goal state has a definite order that is discussed later.

b. Problem Formulation :

  • State Description
  • Initial State & Goal State
  • Actions as function of states
  • Transition Model
  • Step Costs & Path Costs

b.1 State Description :

A state is described by the positions of the tiles and blank in a state array.

Basic terminolgy :

square x - location in the grid, x ϵ [0,8] tile x - a square occupied by the number x ϵ [1,8] blank - unoccupied square.

Clearly, there are finite no. of states in this problem.

b.2 Initial State & Goal State :

Initial state is taken as an input. It can be any possible configuration of the grid i.e., any possible state of the problem.

Goal state for 8-Puzzle is defined differently by various authors. We will consider the following state as the goal state.

b.3 Actions as function of States :

Set of all possible actions in the 8 puzzle problem : { UP, LEFT, DOWN, RIGHT }

All of them represent the possible physical movements of the blank in the grid.

We need a function ACTIONS that takes in state of the problem as an argument and returns all the possible actions that are valid in the given state.

For example, consider the following state :

When ACTIONS is called on the above state, it returns UP,LEFT & DOWN.

To make the representation much simpler, let us quantify the actions.

UP : 1 LEFT : 2 DOWN : 4 RIGHT : 8

Now, if ACTIONS is called on the same state, it returns 1+2+4, i.e., 7.

b.4 Transition Model :

We need a transition model that describes how the grid evolves with different actions taken by the agent.

The transition function takes current state and an action as arguments and returns the resulting state.

b.5 Goal Test :

This function GOALTEST takes in a state as an argument and returns a boolean by checking if the state is the goal or not.

The goal test function returns True for the above state.

b.6 Step Costs & Path Costs :

Every action is associated with some cost. Here, we consider step cost to be 1 for each action. Path cost is the sum of all the step costs in the path(sequence of states).

Whenever there is a transition, we find the path cost recursively.

Consider a transition from state a to state b:   path-cost(b) = path-cost(a) + step-cost(a,b)

Path cost for the initial state is taken as zero.

c. Implementation details :

  • Structure of node

c.1 Algorithm :

We use A* Search to find an optimal sequence of actions that lead to the goal state.

A* Search is a well known informed search algorithm. An informed search algorithm has additional knowledge given to it, that is not provided by the problem description itself. This additional knowledge is known as heuristics.

Check out the following link to know more about A* Search. http://web.mit.edu/eranki/www/tutorials/search/

c.2 Heuristics :

Given a state, heuristics of that state indicates an estimated cost to reach the goal state.

A good heuristic function is admissible and consistent.

Check out the following link to know more about heurisitcs. http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html

For a node n, h(n) = #misplaced tiles and blank in the grid

The above heuristic is both admissible and consistent.

c.3 Structure of node :

We define a node as a structure that holds following information.

state holds state description

actions() member function, returns a set of actions as a number

parent a pointer to the parent node

path-cost the cost of the path to the current node.

Compilation & Running using g++

g++ astar.cpp puzzle.cpp problem.cpp main.cpp -o excutable-name.exe executable-name.exe

Input/Output Format

Consider the following state as the initial state.

The input is space separated integers representing the positions of the tiles from 0 to 8.

The input for the above initial state is, 4 7 6 2 0 1 3 8 5

The goal state is for this problem is,

The output sequence is a series of states showing the optimal path to the goal state. 8 0 1 2 3 4 5 6 7 . . . 4 7 6 2 0 1 3 8 5

explain problem solving agent of 8 puzzle problem

Solving 8-Puzzle using A* Algorithm.

Ajinkya Sonawane

Ajinkya Sonawane

Good Audience

Solving the sliding puzzle using a basic AI algorithm.

Let’s start with what I mean by an “8-Puzzle” problem.

N-Puzzle or sliding puzzle is a popular puzzle that consists of N tiles where N can be 8, 15, 24, and so on. In our example N = 8. The puzzle is divided into sqrt(N+1) rows and sqrt(N+1) columns. Eg. 15-Puzzle will have 4 rows and 4 columns and an 8-Puzzle will have 3 rows and 3 columns. The puzzle consists of N tiles and one empty space where the tiles can be moved. Start and Goal configurations (also called state) of the puzzle are provided. The puzzle can be solved by moving the tiles one by one in the single empty space and thus achieving the Goal configuration.

The tiles in the initial(start) state can be moved in the empty space in a particular order and thus achieve the goal state.

N ote: There are exceptions in N-Puzzle, visit the link below to check if a given problem is solvable or not.

How to check if an instance of 15 puzzle is solvable? - GeeksforGeeks

Given a 4×4 board with 15 tiles (every tile has one number from 1 to 15) and one empty space. the objective is to place….

www.geeksforgeeks.org

Rules for solving the puzzle.

Instead of moving the tiles in the empty space, we can visualize moving the empty space in place of the tile, basically swapping the tile with the empty space. The empty space can only move in four directions viz.,

1. Up 2.Down 3. Right or 4. Left

The empty space cannot move diagonally and can take only one step at a time (i.e. move the empty space one position at a time).

You can read more about solving the 8-Puzzle problem here .

Before we talk about the A* algorithm, we need to discuss Heuristic Search.

Basically, there are two types of searching techniques : 1. Uninformed Search and 2. Informed Search

You might have heard about Linear Search, Binary Search, Depth-First Search, or the Breadth-First Search. These searching algorithms fall into the category of uninformed search techniques i.e. these algorithms do not know anything about what they are searching for and where they should search for it. That’s why the name “uninformed” search. Uninformed searching takes a lot of time to search as it doesn’t know where to head and where the best chances of finding the element are.

Informed search is exactly opposite to the uninformed search. In this, the algorithm is aware of where the best chances of finding the element are and the algorithm heads that way! Heuristic search is an informed search technique. A heuristic value tells the algorithm which path will provide the solution as early as possible. The heuristic function is used to generate this heuristic value. Different heuristic functions can be designed depending on the searching problem. So we can conclude that Heuristic search is a technique that uses a heuristic value for optimizing the search.

A* Algorithm

A* is a computer algorithm that is widely used in pathfinding and graph traversal, the process of plotting an efficiently traversable path between multiple points, called nodes. Noted for its performance and accuracy, it enjoys widespread use. The key feature of the A* algorithm is that it keeps a track of each visited node which helps in ignoring the nodes that are already visited, saving a huge amount of time. It also has a list that holds all the nodes that are left to be explored and it chooses the most optimal node from this list, thus saving time not exploring unnecessary or less optimal nodes. So we use two lists namely ‘open list‘ and ‘closed list‘ the open list contains all the nodes that are being generated and are not existing in the closed list and each node explored after it’s neighboring nodes are discovered is put in the closed list and the neighbors are put in the open list this is how the nodes expand. Each node has a pointer to its parent so that at any given point it can retrace the path to the parent. Initially, the open list holds the start(Initial) node. The next node chosen from the open list is based on its f score , the node with the least f score is picked up and explored.

f-score = h-score + g-score

A* uses a combination of heuristic value (h-score: how far the goal node is) as well as the g-score (i.e. the number of nodes traversed from the start node to current node).

In our 8-Puzzle problem, we can define the h-score as the number of misplaced tiles by comparing the current state and the goal state or summation of the Manhattan distance between misplaced nodes. g-score will remain as the number of nodes traversed from a start node to get to the current node.

From Fig 1, we can calculate the h-score by comparing the initial(current) state and goal state and counting the number of misplaced tiles. Thus, h-score = 5 and g-score = 0 as the number of nodes traversed from the start node to the current node is 0.

How A* solves the 8-Puzzle problem.

We first move the empty space in all the possible directions in the start state and calculate the f-score for each state. This is called expanding the current state. After expanding the current state, it is pushed into the closed list and the newly generated states are pushed into the open list. A state with the least f-score is selected and expanded again. This process continues until the goal state occurs as the current state. Basically, here we are providing the algorithm a measure to choose its actions. The algorithm chooses the best possible action and proceeds in that path. This solves the issue of generating redundant child states, as the algorithm will expand the node with the least f-score .

Implementation of N-Puzzle in Python

I have used two classes in my code: Node & Puzzle. Node class defines the structure of the state(configuration) and also provides functions to move the empty space and generate child states from the current state. Puzzle class accepts the initial and goal states of the N-Puzzle problem and provides functions to calculate the f-score of any given node(state).

Ajinkya-Sonawane/Python

Python. contribute to ajinkya-sonawane/python development by creating an account on github..

Ajinkya Sonawane

Written by Ajinkya Sonawane

Yet Another Developer Developer!

More from Ajinkya Sonawane and Good Audience

Python script to edit Google Sheets | Daily Python #7

Daily Python

Python script to edit Google Sheets | Daily Python #7

This article is a tutorial on how to access and edit google sheets using python and google api..

Confused about OCO Orders on Binance? Here’s an easy explanation

Vamshi Vangapally

Confused about OCO Orders on Binance? Here’s an easy explanation

You might have heard or seen the option to place oco orders on binance. this is called “one cancels the other” orders. let’s explore….

Understanding Zero-knowledge proofs through simple examples

Understanding Zero-knowledge proofs through simple examples

I recently listened to this zkfm podcast, which gave illustrative examples that clearly explained key concepts on zero knowledge proofs. i….

Python script to search content using YouTube Data API | Daily Python #8

Python script to search content using YouTube Data API | Daily Python #8

This article is a tutorial on how to utilize youtube data api using python., recommended from medium.

Roadmap to Learn AI in 2024

Benedict Neo

bitgrit Data Science Publication

Roadmap to Learn AI in 2024

A free curriculum for hackers and programmers to learn ai.

I Built an App in 6 Hours that Makes $1,500/Mo

Artturi Jalli

I Built an App in 6 Hours that Makes $1,500/Mo

Copy my strategy.

explain problem solving agent of 8 puzzle problem

Predictive Modeling w/ Python

explain problem solving agent of 8 puzzle problem

Natural Language Processing

Principal Component Analysis for ML

Practical Guides to Machine Learning

explain problem solving agent of 8 puzzle problem

ChatGPT prompts

The Era of High-Paying Tech Jobs is Over

Somnath Singh

Level Up Coding

The Era of High-Paying Tech Jobs is Over

The death of tech jobs..

Dark web a place of risk: My Dark web story

Kallol Mazumdar

ILLUMINATION

I Went on the Dark Web and Instantly Regretted It

Accessing the forbidden parts of the world wide web, only to realize the depravity of humanity.

6 Steps to Make AI Write Your Python Code for You

Nabil Alouani

Towards Data Science

6 Steps to Make AI Write Your Python Code for You

Use the inspire framework to save time and gain a competitive edge (chatgpt-4 — claude 3 — gemini).

Advice From a Software Engineer With 8 Years of Experience

Benoit Ruiz

Better Programming

Advice From a Software Engineer With 8 Years of Experience

Practical tips for those who want to advance in their careers.

Text to speech

  • Pathfinding
  • Solving 8 puzzle problem using A* star search
  • May 17, 2020 March 27, 2024

Solving 8 puzzle problem using A* star search in C++

This tutorial will solve the 8 puzzle problem using the A* (star) search algorithm. We will approach the solution by first modelling the problem, building the fundamental blocks and finally applying a solver to solve the puzzle.

Part 1 of this tutorial provides the introduction, the background information and the approach towards the solution from the algorithmic point of view.

Part 2 of this tutorial provides an implementation of the algorithm and the solution using C++ for a console program. Read Part 2, “Solving 8 puzzle problem using A* star search in C++” .

Part 3 of this tutorial provides an implementation of the algorithm and the solution using C# for the Unity project. Read Part 2, “ 8-Puzzle Problem Using A* in C# and Unity “ .

Tutorials on Pathfinding and a WebGL Playground for experimenting pathfinding.

explain problem solving agent of 8 puzzle problem

Part 1 – Introduction

Typically A* (Astar) is used in a grid-based pathfinding problem. However, as a general rule, any pathfinding algorithm (A* included) can be used to solve any graph-based problem. For a very detailed understanding of path-finding, I suggest the brilliant tutorial maintained by Amit on Stanford’s site . In this tutorial, I will not go through the theory of A* pathfinding, but rather, I would implement all necessary functions for A* pathfinding to solve the 8 puzzle problem.

The 8 Puzzle Problem

The 8 puzzle problem is a puzzle that was invented and popularised by Noyes Palmer Chapman in the 1870s. The 8-puzzle is a smaller version of the slightly better-known 15-puzzle. It comprises a 3-by-3 grid with 8 square blocks labelled 1 through 8 and a blank square.

The goal is to rearrange the blocks so that they are in order. The blank tile can sometimes be at the start or the end. The diagram above shows one possible initial configuration and the goal. You are permitted to slide blocks horizontally or vertically into the blank square to reach the goal state.

Start and goal graphical representation

Before we can solve the 8 puzzle problem, we will need to model the problem. But what is meant by Modelling the Problem?

In generic terms, modelling a problem is the art of formulating the problem at hand in terms of precisely described, well-understood building blocks and logic to reach a solution. In computer science, proper modelling is the key to applying algorithmic design techniques to any real-world problem. Real-world applications involve real-world problems.

You might be working on a system that simulates air traffic in and around an airport, you might be working on optimising the dispatch of delivery vans for an e-commerce application, or you might be working to search through patterns in a large image set. To solve such problems, you will use some modelling techniques to reduce the problem in rigorously defined abstract structures such as graphs, trees, permutations, sets, etc.

For our 8 puzzle problems, let’s see how we can model the problem. Let’s take a random state of the 8 puzzle problem as given in the diagram below. We can either slide tile 8 up, slide 3 right, or slide 6 left to create three variant states from this random state.

The variant states from a given state in 8-puzzle

These three states will produce subsequent more states (3 for the first, 1 for the second and 1 for the third). This continues until we find the goal state.

We can see that we can transform the various possible states of the 8 puzzle problem into a tree data structure.

The state tree for an 8-puzzle

The 8 Puzzle Solution Search Space

The 8-puzzle is the largest possible N-puzzle that can be solved entirely. It is simple and yet has a significant problem space. There are larger variants to the same problem type, like the 15-puzzle. But those cannot be solved to completion. This complexity makes the N x N extension of the 8-puzzle an NP-hard problem.

8 puzzle has 9! possible tile permutation states. Out of these, every second permutation state is solvable. Hence, there is a total of 9!/2 = 181,440 solvable problem states.

Alexander Reinefeld from the Paderborn Center for Parallel Computing , Germany, has shown that the average length of all optimal solution paths is about 22 moves for any given random configuration. For the 181440 solvable configurations, there is a total of 500880 optimal solutions. This gives an average solution density of 2.76 per problem, with the minimum and maximum number lying at 1 and 64 solutions.

The problem lies in creating the possible search tree and then traversing the most optimal tree branch that will lead from the start state to the end state.

So, how do we find the most optimal branch of the tree? Enter the Heuristic Search!

Heuristic Search

A Heuristic search is a technique to solve a search problem faster than classical methods. In many cases, it finds an approximate solution when classical methods cannot. It is thus a generalized and approximate strategy for problem-solving.

In layman’s terms, it can be thought of as a rule of thumb, or a common-sense knowledge, where the answer isn’t guaranteed to be correct but helps to reach a decision quickly. It is a shortcut that we take to trade-off either the optimality, the completeness, the accuracy, or the precision for speed.

Heuristic searches are often associated with heuristic values.

A heuristic value of a node in the construction graph attempts to capture the importance of that node’s value, for example, the cost or the gain. Heuristic search is a type of informed search that uses such a heuristic value for optimising the search .

At each branching step, the search evaluates the heuristic value and decides which branch to follow. It does so by ranking alternatives.

There are many different types of heuristic search algorithms. One of them is the A* search algorithm.

The A* Search

A* search is a computer search algorithm that is widely used for pathfinding and graph traversal. In our case of the 8 puzzle problem, we will be using it for optimal graph traversal. A* works by keeping track of all visited nodes and ignoring them for further traversal. At the same time, it also keeps track of all the nodes that are yet to be explored and chooses one with the least cost to be further explored.

This simple mechanism allows us to find the most optimal tree branch that will lead us from the start state to the end state.

The Heuristic Value (Cost Function) of an 8 Puzzle State

The heuristic value of an 8 puzzle state is a combination of two values. It is often called the cost function f .

h gives how far the goal node is and g the number of nodes traversed from the start node to the current node. For h, we will use the Manhattan distance, and for g, we will use the depth of the current node.

For our A* search, we will use the sum of Manhattan distance and the current depth of the node as the total cost.

Manhattan distance

The Manhattan distance heuristic is used for its simplicity and ability to estimate the number of moves required to bring a given puzzle state to the solution state. Manhattan distance is computed by the sum of the distances of each tile from where it should belong.

For example, the Manhattan distance between “213540678” and “123456780” is 9 and between “647850321” and “123456780” is 21.

The diagram below shows the Manhattan cost for a specific tiles configuration.

Manhattan distance calculation for 8-puzzle state

Software Design for Solving 8 Puzzle Problem

In the following section, I will start creating the building blocks for the puzzle solution and finally try to join them to reach the solution.

The first step towards solving the 8 puzzle problem will require a data type to represent the tiles on the puzzle. I will call this the State of the puzzle. A state is a unique combination of tiles.

During our process of solving, we will need to store hundreds of perhaps thousands of tile states. Each combination of tiles in the puzzle will be a unique state. Each unique state of the tiles will represent a Node in the tree data structure.

I will use an integer array to represent a state. The array indices will refer to a tile location, whereas the value in that index will represent the tile number. Look at the diagram below. In this diagram, a unique state of the tile is shown on the left. On the right, an array representation is shown to store the tile information.

Start state graphics representation and index array representation.

Thus, we see that we can represent any state of the 8 puzzle problem by using a one-dimensional array. The indices of the array, which cannot change, represent the fixed location of the tiles. In our case, we have assumed that array index 0 represents the top-left tile, index 1 as top-centre tile, index 2 as top-right tile and so on until index 8 as the bottom-right tile. The value stored in each index will represent the actual number (or picture) on the tile. For example, in the above case, we have index 0 having tile 0 (or the empty tile), index 1 having tile 3 and until index 8 with tile 2.

We can thus see that we can arrive at the goal state by manipulating the values on the array, with the constraint of where the empty tile slides into for each move.

The graphical representation of 8-puzzle goal state

After State is defined, our next task would be to create the graph of neighbours for the 8 puzzle problem.

We have defined the state in the previous section. Now we will define the neighbours based on where the empty tile is. We will do this for each of the 9 tile indices.

So let’s start with tile index 0. For every index, we will need to store the neighbours (in other words, the indices where the empty tile can move) as a collection of indices.

Looking at the above list, we can now access the neighbours for any tile index. For example, for tile index 6, the neighbours are tile indices 7 and 3.

For the first figure below, we have our empty tile in index 0. So for index 0, the neighbours are index 1 and 3. Please note that I am referring to the index of the array and not the actual value of that element in that index of the array. In the first figure below, index 1 is 3, and index 3 is 4. Neighbours, in this case, are index 1 and index 3.

Neighbour indices for 3 random states of 8-puzzle

Similarly, for the state represented by the second figure, the empty tile index is 2. Neighbours, in this case, are 1 and 5. For the third state, represented by the third figure, the empty index is 1, and neighbours are 0, 2 and 4. We can thus form a dictionary (or map) of neighbours for each of the 9 indices.

Node (or the State Tree)

The state tree is the actual tree that comprises all the valid transitions from one state to another state, ultimately reaching the final goal (if the solution exists).

In computer science, a tree is a widely used abstract data type (ADT)—or data structure implementing this ADT—that simulates a hierarchical tree structure, with a root value and subtrees of children with a parent node, represented as a set of linked nodes – source Wikipedia .

Each tree element we call Node will comprise one specific tile for an 8 puzzle for this problem.

Solver for 8 Puzzle

Finally, we look at the Solver framework. The Solver should be able to solve the puzzle based on the A* algorithm. The solver will be implemented simply as a main console function in C++ and a Coroutine in the Unity C# version. The solver class will construct the tree, visit the next best node and collect nodes for the solution until the solution is finally found.

Read Part 2 of the tutorial “Solving 8 puzzle problem using A* star search in C++.”

Read Part 3 of the tutorial “ 8-Puzzle Problem Using A* in C# and Unity. “

Read My Other Tutorials

  • Implement a Generic Pathfinder in Unity using C#
  • Create a Jigsaw Puzzle Game in Unity
  • Generic Finite State Machine Using C#
  • Implement Bezier Curve using C# in Unity
  • Create a Jigsaw Tile from an Existing Image
  • Create a Jigsaw Board from an Existing Image
  • A Configurable Third-Person Camera in Unity
  • Player Controls With Finite State Machine Using C# in Unity
  • Finite State Machine Using C# Delegates in Unity
  • Enemy Behaviour With Finite State Machine Using C# Delegates in Unity
  • Augmented Reality – Fire Effect using Vuforia and Unity
  • Implementing a Finite State Machine Using C# in Unity
  • Solving 8 puzzle problem using A* star search in C++
  • What Are C# Delegates And How To Use Them
  • How to Generate Mazes Using Depth-First Algorithm

Shamim Akhtar

A  committed and optimistic professional who brings passion and enthusiasm to help motivate, guide and mentor young students into their transition to the Industry and reshape their careers for a fulfilling future. The past is something that you cannot undo. The future is something that you can build .

I enjoy coding, developing games and writing tutorials.  Visit my GitHub to see the projects I am working on right now. Educator | Developer | Mentor

5 thoughts on “Solving 8 puzzle problem using A* star search”

explain problem solving agent of 8 puzzle problem

Simply want to say your article is as astonishing. The clarity in your post is just great and i could assume you’re an expert on this subject.

Fine with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please continue the gratifying work.

explain problem solving agent of 8 puzzle problem

Wow! After all I got a website from where I be capable of actually get useful information regarding my study and knowledge.

explain problem solving agent of 8 puzzle problem

Wow, incredible blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is fantastic, let alone the content!

explain problem solving agent of 8 puzzle problem

Ꭺwesome post.

explain problem solving agent of 8 puzzle problem

bookmarked!!, I ⅼove your web site!

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

{{#message}}{{{message}}}{{/message}}{{^message}}Your submission failed. The server responded with {{status_text}} (code {{status_code}}). Please contact the developer of this form processor to improve this message. Learn More {{/message}}

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More {{/message}}

Submitting…

1 3 1 3 1 2 3 1 2 3 1 2 3 4 2 5 => 4 2 5 => 4 5 => 4 5 => 4 5 6 7 8 6 7 8 6 7 8 6 7 8 6 7 8 initial goal
8 1 3 1 2 3 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 4 2 4 5 6 ---------------------- ---------------------- 7 6 5 7 8 1 1 0 0 1 1 0 1 1 2 0 0 2 2 0 3 initial goal Hamming = 5 + 0 Manhattan = 10 + 0
8 1 3 8 1 3 8 1 3 4 2 4 2 4 2 7 6 5 7 6 5 7 6 5 previous state disallow
% more puzzle04.txt 3 0 1 3 4 2 5 7 8 6 % java Solver 1 3 4 2 5 7 8 6 1 3 4 2 5 7 8 6 1 2 3 4 5 7 8 6 1 2 3 4 5 7 8 6 1 2 3 4 5 6 7 8 Number of states enqueued = 10 Minimum number of moves = 4
% more puzzle-impossible3x3.txt 3 1 2 3 4 5 6 8 7 0 % java Solver No solution possible
public class Board { public Board(int[][] tiles) // construct a board from an N-by-N array of tiles public int hamming() // return number of blocks out of place public int manhattan() // return sum of Manhattan distances between blocks and goal public boolean equals(Object y) // does this board position equal y public Iterable<Board> neighbors() // return an Iterable of all neighboring board positions public String toString() // return a string representation of the board } public class Solver { public Solver(Board initial) // find a solution to the initial board public boolean isSolvable() // is the initial board solvable? public int moves() // return min number of moves to solve initial board; -1 if no solution public Iterable<Board> solution() // return an Iterable of board positions in solution }
public static void main(String[] args) { int N = StdIn.readInt(); int[][] tiles = new int[N][N]; for (int i = 0; i

Recent Trends in Solving the 8-Puzzle Problem

Ieee account.

  • Change Username/Password
  • Update Address

Purchase Details

  • Payment Options
  • Order History
  • View Purchased Documents

Profile Information

  • Communications Preferences
  • Profession and Education
  • Technical Interests
  • US & Canada: +1 800 678 4333
  • Worldwide: +1 732 981 0060
  • Contact & Support
  • About IEEE Xplore
  • Accessibility
  • Terms of Use
  • Nondiscrimination Policy
  • Privacy & Opting Out of Cookies

A not-for-profit organization, IEEE is the world's largest technical professional organization dedicated to advancing technology for the benefit of humanity. © Copyright 2024 IEEE - All rights reserved. Use of this web site signifies your agreement to the terms and conditions.

The Problem

The 8-puzzle is a smaller version of the slightly better known 15-puzzle. The puzzle consists of an area divided into a grid, 3 by 3 for the 8-puzzle, 4 by 4 for the 15-puzzle. On each grid square is a tile, expect for one square which remains empty. Thus, there are eight tiles in the 8-puzzle and 15 tiles in the 15-puzzle. A tile that is next to the empty grid square can be moved into the empty space, leaving its previous position empty in turn. Tiles are numbered, 1 thru 8 for the 8-puzzle, so that each tile can be uniquely identified.

The aim of the puzzle is to achieve a given configuration of tiles from a given (different) configuration by sliding the individual tiles around the grid as described above.

Searching for a Solution

This problem can be solved by searching for a solution, which is a sequence of actions (tile moves) that leads from the initial state to the goal state. Two possible states of the 8-puzzle are shown in figure 1. The state on the right is a typical goal state. The state on the left is a configuration that represents a worst case: transforming this state into the goal state requires at least 31 actions, which is the diameter of the search space. For search algorithms the problem is often to find the shortest solution, that is, one which consists of the least number of tile moves.

explain problem solving agent of 8 puzzle problem

The EightPuzzleApp Java Application

EightPuzzleApp is a Java application that explores the above search space using a number of (uninformed) search strategies. Download the application and double-click it. Alternatively, run the command "java -jar EightPuzzleApp.jar" from the command line. Either should bring up a window that looks essentially like the one shown in figure 2.

explain problem solving agent of 8 puzzle problem

To search for a solution, first select a search strategy. Next, there are some configuration options for the search process. If the search space is to be searched as a graph, multiple paths leading to the same node will usually only be explored once. In a tree, search states that can be reached by multiple paths will also be explored multiple times. The number of states to be generated can be limited to the given value, resulting in the search being abandoned at that point. For a depth-first search it is also possible to set a depth limit, meaning no states at a greater depth will be explored.

To start the serach press the Step or Search button. This will bring up a dialog box that confirms the input state. The default value is the left puzzle in figure 1 represented as the string:

This string is simply a line by line enumeration of the tile numbers, where 0 (zero) represents the empty space. Type in a different state if required or accept the current state.

Finally, a trace of the search can be written to the window and/or a text file. Note that this may cause the JVM to run out of memory if the trace is written to the window! The operation performed by a search engine consists of selecting a current search node and generating its successors, and the trace reflects this process. For example, the line:

indicates that the selected node contains the given state. The number (11 in the example) is the unique identifier for the search node. Note that there may be multiple nodes that contain the same state, especially when tree search is performed. Then there is a description of the selected state which is similar to the input, namely a line by line enumeration of the tiles. The lines following this one in the trace describe the successor states that have been generated, for example:

So, expanding the given search node (11) resulted in two new search nodes (12, 13 and 14).

Even with tracing off the window will display some information about the search (which is not part of the trace). It will show how many states have been explored (the goal test has been performed and successors have been generated) and how many states have been generated (explored states plus fringe nodes). If a solution is found this will also be printed. Finally, the elapsed time taken to perform the search is printed. Note that writing the trace usually takes more time than searching itself.

S. Russell and P. Norvig. Artificial Intelligence: A Modern Approach, chapter 3. Prentice Hall, 2nd edition, 2003.

Wikipedia.org: Fifteen puzzle

8 Puzzle Problem

The 8-puzzle is a square board with 9 positions, filled by 8 numbered tiles and one gap. At any point, a tile adjacent to the gap can be moved into the gap, creating a new gap position. In other words the gap can be swapped with an adjacent (horizontally and vertically) tile. The objective in the game is to begin with an arbitrary configuration of tiles, and move them so as to get the numbered tiles arranged in ascending order either running around the perimeter of the board or ordered from left to right, with 1 in the top left-hand position. An example scenario is shown below.

Here the goal state can be reached from the initial state at 5 simple steps given below.

  • Blank Right

As mentioned earlier the goal state has two possible arrangements. These arrangements can be:

Solving the 8-Puzzle with A* and SimpleAI

Discover Heuristic-Based Problem Solving

Welcome to a comprehensive exploration into the world of Informed Search Heuristics with a captivating use case - the 8-Puzzle . Leveraging Python and its powerful libraries, we’ll delve into solving the 8-puzzle problem. This project covers:

  • The basics of Informed Search Heuristics and their significance in artificial intelligence.
  • Understanding the 8-Puzzle problem and its representation.
  • The implementation of A* algorithm to solve the 8-Puzzle.
  • The application of Manhattan Distance and Misplaced Tiles as heuristics in our problem.
  • A detailed guide to coding the solution with Python .
  • An in-depth analysis of the solution and the impact of different heuristics on the efficiency of the solution.

This insightful journey is beneficial for both AI beginners and seasoned researchers . The project offers a deep understanding of Informed Search Heuristics and their practical implementation in the 8-Puzzle problem .

Informed Search Heuristics

Informed Search Heuristics play a pivotal role in the domain of artificial intelligence. Heuristics are techniques that guide the search process towards more promising regions, thus reducing the search time. They are based on information (hence “informed”) that is available a priori and can provide an estimate to the solution from any given state.

Application in Artificial Intelligence

Heuristics are often used in path-finding problems, scheduling, and in the game industry. They are a cornerstone of the A* search algorithm, which combines the benefits of Breadth-First Search (completeness and optimality) and Depth-First Search (space-efficiency) and is used widely due to its effectiveness and efficiency. For instance, the paper ‘Search-Based Optimal Solvers for the Multi-Agent Pathfinding Problem: Summary and Challenges’ discusses various search-based techniques developed for optimally solving Multi-agent pathfinding (MAPF) under the sum-of-costs objective function 1 . Similarly, ‘Multi-Agent Pathfinding with Simultaneous Execution of Single-Agent Primitives’ proposes an algorithm for multi-agent pathfinding that utilizes single-agent primitives but allows all agents to move in parallel 2 . These examples illustrate the practical application and effectiveness of heuristics in solving complex problems.

The 8-Puzzle Problem

The 8-Puzzle problem is a puzzle that was invented and popularized by Noyes Palmer Chapman in the late 19th century. It consists of a 3x3 grid with eight numbered tiles and a blank space. The goal is to reach a specified goal state from a given start state by sliding the blank space up, down, left or right.

Visualizing the Program Flow and Execution

We have prepared a series of diagrams to provide a better understanding of the program flow and execution of our 8-puzzle solution, including the utilization of the A* Search Algorithm:

These diagrams help you visualize the flow of control and object, structure of the classes used, and the sequence of operations in our implementation to solve the 8-Puzzle problem.

GitHub Repository

For complete access to the code and resources associated with this project, visit our GitHub repository:

Interactive Document Preview

Immerse yourself in the 8-Puzzle project write-up with our interactive document preview. Navigate, zoom in, scroll through, and engage with the content freely.

To access the project write-up in PDF format for offline reading or printing, download from the link below.

By implementing Informed Search Heuristics and using the A* search algorithm, we’ve developed an efficient solution to the 8-Puzzle problem. This project demonstrates the efficacy of Informed Search Heuristics and A* in problem-solving tasks and provides valuable insights into their workings. As we delve deeper into the field of Artificial Intelligence, we can apply these concepts to other problem-solving tasks and real-world applications.

Join the Discussion

We welcome your thoughts, inquiries, and experiences related to the 8-Puzzle project! Engage in our Disqus forum below. Share your insights, ask questions, and connect with others passionate about Informed Search Heuristics and problem-solving.

Feel free to share your ideas or ask for help; we’re all in this together. Let’s build a vibrant community to discuss, learn, and explore the exciting world of Informed Search Heuristics and their application in problems like the 8-Puzzle.

Do provide us with feedback and share with us how we could make this write-up more beneficial for you! We are always eager to learn and improve.

Insight Tribune

Ignite Your Mind and Illuminate Your World

Solving the 8-Puzzle Problem with AI: A Python Code Tutorial

explain problem solving agent of 8 puzzle problem

Are you looking for a way to solve the infamous 8-puzzle problem using AI? You’ve come to the right place! In this tutorial, we’ll walk you through the process of solving the 8-puzzle problem using Python code. But before we dive into the nitty-gritty, let’s first understand what the 8-puzzle problem is.

What is the 8-puzzle problem?

The 8-puzzle problem is a classic problem in artificial intelligence that involves moving tiles on a 3×3 board. The goal is to arrange the tiles in a particular order with the empty space at the bottom right corner. Sounds easy, right? Think again. There are trillions of possible combinations, making it a challenging problem to solve. That’s why we need AI to help us tackle it.

How does AI solve the 8-puzzle problem?

There are several approaches to solve the 8-puzzle problem using AI, but we’ll focus on using the A* search algorithm. A* search is a heuristic search strategy that finds the shortest path between a start node and a goal node. In our case, the start node is the initial configuration of the puzzle and the goal node is the solution configuration.

The A* search algorithm uses a heuristic function to estimate the cost of reaching the goal node from each node in the search space. The heuristic function we’ll use is the Manhattan distance, which measures the sum of the distances of each tile from its goal position.

Implementing the A* search algorithm

To implement the A* search algorithm in Python, we need to define a class for the puzzle state, which includes the puzzle configuration, the empty tile position, and the cost to reach the current state. We’ll also define a class for the search node, which includes the puzzle state, the parent node, and the total cost to reach the current node.

We’ll then define a function to generate the successors of a given state, which are the possible moves from the empty tile position. We’ll use the successors to expand the search space until we reach the goal configuration.

Complete code example

“`python # Define the initial and goal configurations initial_state = [[2, 8, 3], [1, 6, 4], [7, 0, 5]]

goal_state = [[1, 2, 3], [8, 0, 4], [7, 6, 5]]

# Define the puzzle state class class PuzzleState: def __init__(self, config, empty_pos, cost): self.config = config self.empty_pos = empty_pos self.cost = cost

# Define the search node class class SearchNode: def __init__(self, state, parent, total_cost): self.state = state self.parent = parent self.total_cost = total_cost

In conclusion, we’ve shown you how to solve the 8-puzzle problem using AI with a Python code tutorial. We’ve explained what the 8-puzzle problem is, how AI can solve it using the A* search algorithm, and provided a complete code example. By following this tutorial, you can now implement the A* search algorithm to solve the 8-puzzle problem on your own.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Related Posts

explain problem solving agent of 8 puzzle problem

  • Explorations

The Importance of Regular Checkups: Insights from the South Carolina Health Department

  • Aiden Scholar
  • June 9, 2023

when it comes to taking care of our health, it's easy to put things off…

explain problem solving agent of 8 puzzle problem

Why Personal Coaching Courses are Worth the Investment

  • June 12, 2023

personal coaching courses are becoming increasingly popular as people seek to improve various aspects of…

explain problem solving agent of 8 puzzle problem

Discovering the Best Beaches in the Philippines with 2GO Travel

  • June 10, 2023

the best beaches in the philippines with 2go travel: a guide the philippines is known…

explain problem solving agent of 8 puzzle problem

Exploring Robotics in Hawaii: A Look into the Future

  • June 11, 2023

exploring robotics in hawaii: a look into the future

Solving an Eight Puzzle

To get a better sense of how heuristic search works, and to see how this same process can be used to solve other kinds of problems, we are going to solve an "eight puzzle". In this puzzle, you have 8 squares in a 3x3 grid with one open square. You make moves by sliding a piece that is next to the empty square into the gap. The goal is to rearrange the 8 pieces into a particular picture or pattern.

Click here for an 8 puzzle you can try solving

To guide our search we need to come up with a heuristic - something that does a pretty good job of estimating the amount of work that remains. Since each move can only move one piece, if there are 4 pieces out of position, we know there are at least 4 more moves to go. That suggests we can at any point look at a board and estimate the remaining work by counting up the number of pieces that are not in the right place according to the goal. If we add that estimate of future work to the amount of work it takes to get to any state, we can estimate how much work the total path to the goal will be if we go through that state.

$\textrm{estimated cost} = \textrm{moves so far } + \textrm{ pieces still out of place}$

When we pick a state to explore next we will always choose the one with the smallest estimated total cost.

Note that the empty location does not count as an "out of place" piece

Note that we could have slid the 6 back up to the middle, but that would get us back to the same board as the starting state but having used two moves. There is no reason we would want to do that... so we are omitting that move. In general, if a move would produce a board we have already seen how to make with fewer moves we will ignore it.

  • Getting started with algorithm
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • A* Pathfinding
  • A* Pathfinding through a maze with no obstacles
  • Introduction to A*
  • Solving 8-puzzle problem using A* algorithm
  • A* Pathfinding Algorithm
  • Algo:- Print a m*n matrix in square wise
  • Algorithm Complexity
  • Applications of Dynamic Programming
  • Applications of Greedy technique
  • Bellman–Ford Algorithm
  • Big-O Notation
  • Binary Search Trees
  • Binary Tree traversals
  • Breadth-First Search
  • Bubble Sort
  • Bucket Sort
  • Catalan Number Algorithm
  • Check if a tree is BST or not
  • Check two strings are anagrams
  • Counting Sort
  • Depth First Search
  • Dijkstra’s Algorithm
  • Dynamic Programming
  • Dynamic Time Warping
  • Edit Distance Dynamic Algorithm
  • Equation Solving
  • Fast Fourier Transform
  • Floyd-Warshall Algorithm
  • Graph Traversals
  • Greedy Algorithms
  • Hash Functions
  • Insertion Sort
  • Integer Partition Algorithm
  • Knapsack Problem
  • Knuth Morris Pratt (KMP) Algorithm
  • Kruskal's Algorithm
  • Line Algorithm
  • Longest Common Subsequence
  • Longest Increasing Subsequence
  • Lowest common ancestor of a Binary Tree
  • Matrix Exponentiation
  • Maximum Path Sum Algorithm
  • Maximum Subarray Algorithm
  • Multithreaded Algorithms
  • Odd-Even Sort
  • Online algorithms
  • Pancake Sort
  • Pascal's Triangle
  • Pigeonhole Sort
  • polynomial-time bounded algorithm for Minimum Vertex Cover
  • Prim's Algorithm
  • Selection Sort
  • Shortest Common Supersequence Problem
  • Sliding Window Algorithm
  • Substring Search
  • Travelling Salesman

algorithm A* Pathfinding Solving 8-puzzle problem using A* algorithm

Fastest entity framework extensions.

Problem definition :

An 8 puzzle is a simple game consisting of a 3 x 3 grid (containing 9 squares). One of the squares is empty. The object is to move to squares around into different positions and having the numbers displayed in the "goal state".

8-puzzle

Given an initial state of 8-puzzle game and a final state of to be reached, find the most cost-effective path to reach the final state from initial state.

Initial state :
Final state :
Heuristic to be assumed :

Let us consider the Manhattan distance between the current and final state as the heuristic for this problem statement.

Total cost function :

So the total cost function f(n) is given by,

Solution to example problem :

First we find the heuristic value required to reach the final state from initial state. The cost function, g(n) = 0, as we are in the initial state

The above value is obtained, as 1 in the current state is 1 horizontal distance away than the 1 in final state. Same goes for 2 , 5 , 6 . _ is 2 horizontal distance away and 2 vertical distance away. So total value for h(n) is 1 + 1 + 1 + 1 + 2 + 2 = 8. Total cost function f(n) is equal to 8 + 0 = 8.

Now, the possible states that can be reached from initial state are found and it happens that we can either move _ to right or downwards.

So states obtained after moving those moves are:

Again the total cost function is computed for these states using the method described above and it turns out to be 6 and 7 respectively. We chose the state with minimum cost which is state (1). The next possible moves can be Left, Right or Down. We won't move Left as we were previously in that state. So, we can move Right or Down.

Again we find the states obtained from (1).

(3) leads to cost function equal to 6 and (4) leads to 4. Also, we will consider (2) obtained before which has cost function equal to 7. Choosing minimum from them leads to (4). Next possible moves can be Left or Right or Down. We get states:

We get costs equal to 5, 2 and 4 for (5), (6) and (7) respectively. Also, we have previous states (3) and (2) with 6 and 7 respectively. We chose minimum cost state which is (6). Next possible moves are Up, and Down and clearly Down will lead us to final state leading to heuristic function value equal to 0.

Got any algorithm Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

8 Puzzle Solver

A simple 8 puzzle solver. (With your choice of heuristic function and search algorithm!) | I first wrote an 8 puzzle solver some years in my university Artificial Intelligence class. That version was a terminal program written in Python.

I first wrote an 8 puzzle solver some years in my university Artificial Intelligence class. That version was a terminal program written in Python. The purpose of that project was to learn about – and then characterize the performance of – different search algorithms and heuristic functions. Feel free to get the code on Github.

Above is a web port of my python project. Enjoy solving puzzles and exploring the performance characteristics of different search algorithms! If you're interested in the details of the algorithms, keep reading.

Search algorithms

The search algorithms used in this project are:

  • Breadth First Search
  • Greedy Best First Search

Breadth First Search is a simple search algorithm that explores the search space in a breadth-first manner. This means that it will explore all the nodes at a given depth before moving on to the next depth. In this case, each node represents some state of the puzzle. This algorithm is guaranteed to find the shortest path to the goal state, but it is also the slowest of the three algorithms.

Greedy Best First Search is a search algorithm that explores the search space in a manner that prioritizes the nodes that are closest to the goal state using some heuristic function. The heuristic function makes a guess which child node is most likely to lead to the goal state. This algorithm is faster than Breadth First Search, but it is not guaranteed to find the shortest path to the goal state.

A* Search is a search algorithm that combines the best of Breadth First Search and Greedy Best First Search. As it explores, it keeps track of the cost of the path to each node. This cost is the sum of the cost of the path to the parent node and the cost of the action that led to the child node. Keeping track of this cost allows A* Search to find the shortest path to the goal state while still exploring the search space with a heuristic to help. This algorithm is often slower than Greedy Best First Search, but it is guaranteed to find the shortest path to the goal state.

Heuristic functions

The heuristic functions used in this project are:

  • Manhattan Distance
  • Hamming Distance

Manhattan Distance is a heuristic function that estimates the cost of the cheapest path from the current state to the goal state. It does this by summing the distances of each tile from its goal position. The distance of a tile is the sum of the horizontal and vertical distances between the tile and its goal position.

Hamming Distance is slightly different. It estimates the cost of the cheapest path from the current state to the goal state by counting the number of tiles that are not in their goal position regardless of their distance from their goal position.

A note on admissibility.

Both of these heuristic functions are admissible. Admissible means that the heuristic function will never overestimate the cost of the cheapest path from the current state to the goal state. This is important because if a heuristic function is not admissible, then the search algorithm may not find the shortest path to the goal state.

Performance Testing

Box Of Notes

Problem Solving Agents in Artificial Intelligence

In this post, we will talk about Problem Solving agents in Artificial Intelligence, which are sort of goal-based agents. Because the straight mapping from states to actions of a basic reflex agent is too vast to retain for a complex environment, we utilize goal-based agents that may consider future actions and the desirability of outcomes.

You Will Learn

Problem Solving Agents

Problem Solving Agents decide what to do by finding a sequence of actions that leads to a desirable state or solution.

An agent may need to plan when the best course of action is not immediately visible. They may need to think through a series of moves that will lead them to their goal state. Such an agent is known as a problem solving agent , and the computation it does is known as a search .

The problem solving agent follows this four phase problem solving process:

  • Goal Formulation: This is the first and most basic phase in problem solving. It arranges specific steps to establish a target/goal that demands some activity to reach it. AI agents are now used to formulate goals.
  • Problem Formulation: It is one of the fundamental steps in problem-solving that determines what action should be taken to reach the goal.
  • Search: After the Goal and Problem Formulation, the agent simulates sequences of actions and has to look for a sequence of actions that reaches the goal. This process is called search, and the sequence is called a solution . The agent might have to simulate multiple sequences that do not reach the goal, but eventually, it will find a solution, or it will find that no solution is possible. A search algorithm takes a problem as input and outputs a sequence of actions.
  • Execution: After the search phase, the agent can now execute the actions that are recommended by the search algorithm, one at a time. This final stage is known as the execution phase.

Problems and Solution

Before we move into the problem formulation phase, we must first define a problem in terms of problem solving agents.

A formal definition of a problem consists of five components:

Initial State

Transition model.

It is the agent’s starting state or initial step towards its goal. For example, if a taxi agent needs to travel to a location(B), but the taxi is already at location(A), the problem’s initial state would be the location (A).

It is a description of the possible actions that the agent can take. Given a state s, Actions ( s ) returns the actions that can be executed in s. Each of these actions is said to be appropriate in s.

It describes what each action does. It is specified by a function Result ( s, a ) that returns the state that results from doing action an in state s.

The initial state, actions, and transition model together define the state space of a problem, a set of all states reachable from the initial state by any sequence of actions. The state space forms a graph in which the nodes are states, and the links between the nodes are actions.

It determines if the given state is a goal state. Sometimes there is an explicit list of potential goal states, and the test merely verifies whether the provided state is one of them. The goal is sometimes expressed via an abstract attribute rather than an explicitly enumerated set of conditions.

It assigns a numerical cost to each path that leads to the goal. The problem solving agents choose a cost function that matches its performance measure. Remember that the optimal solution has the lowest path cost of all the solutions .

Example Problems

The problem solving approach has been used in a wide range of work contexts. There are two kinds of problem approaches

  • Standardized/ Toy Problem: Its purpose is to demonstrate or practice various problem solving techniques. It can be described concisely and precisely, making it appropriate as a benchmark for academics to compare the performance of algorithms.
  • Real-world Problems: It is real-world problems that need solutions. It does not rely on descriptions, unlike a toy problem, yet we can have a basic description of the issue.

Some Standardized/Toy Problems

Vacuum world problem.

Let us take a vacuum cleaner agent and it can move left or right and its jump is to suck up the dirt from the floor.

The state space graph for the two-cell vacuum world.

The vacuum world’s problem can be stated as follows:

States: A world state specifies which objects are housed in which cells. The objects in the vacuum world are the agent and any dirt. The agent can be in either of the two cells in the simple two-cell version, and each call can include dirt or not, therefore there are 2×2×2 = 8 states. A vacuum environment with n cells has n×2 n states in general.

Initial State: Any state can be specified as the starting point.

Actions: We defined three actions in the two-cell world: sucking, moving left, and moving right. More movement activities are required in a two-dimensional multi-cell world.

Transition Model: Suck cleans the agent’s cell of any filth; Forward moves the agent one cell forward in the direction it is facing unless it meets a wall, in which case the action has no effect. Backward moves the agent in the opposite direction, whilst TurnRight and TurnLeft rotate it by 90°.

Goal States: The states in which every cell is clean.

Action Cost: Each action costs 1.

8 Puzzle Problem

In a sliding-tile puzzle , a number of tiles (sometimes called blocks or pieces) are arranged in a grid with one or more blank spaces so that some of the tiles can slide into the blank space. One variant is the Rush Hour puzzle, in which cars and trucks slide around a 6 x 6 grid in an attempt to free a car from the traffic jam. Perhaps the best-known variant is the 8- puzzle (see Figure below ), which consists of a 3 x 3 grid with eight numbered tiles and one blank space, and the 15-puzzle on a 4 x 4  grid. The object is to reach a specified goal state, such as the one shown on the right of the figure. The standard formulation of the 8 puzzles is as follows:

STATES : A state description specifies the location of each of the tiles.

INITIAL STATE : Any state can be designated as the initial state. (Note that a parity property partitions the state space—any given goal can be reached from exactly half of the possible initial states.)

ACTIONS : While in the physical world it is a tile that slides, the simplest way of describing action is to think of the blank space moving Left , Right , Up , or Down . If the blank is at an edge or corner then not all actions will be applicable.

TRANSITION MODEL : Maps a state and action to a resulting state; for example, if we apply Left to the start state in the Figure below, the resulting state has the 5 and the blank switched.

A typical instance of the 8-puzzle

GOAL STATE :  It identifies whether we have reached the correct goal state. Although any state could be the goal, we typically specify a state with the numbers in order, as in the Figure above.

ACTION COST : Each action costs 1.

You Might Like:

  • Agents in Artificial Intelligence

Types of Environments in Artificial Intelligence

  • Understanding PEAS in Artificial Intelligence
  • River Crossing Puzzle | Farmer, Wolf, Goat and Cabbage

Share Article:

Digital image processing: all you need to know.

IMAGES

  1. Eight puzzle problem

    explain problem solving agent of 8 puzzle problem

  2. Solving 8-Puzzle using A* Algorithm

    explain problem solving agent of 8 puzzle problem

  3. 8 Puzzle Problem-Artificial Intelligence-Unit-1-Problem Solving-Problem

    explain problem solving agent of 8 puzzle problem

  4. Solving 8 puzzle problem using A* star search

    explain problem solving agent of 8 puzzle problem

  5. PPT

    explain problem solving agent of 8 puzzle problem

  6. Artificial Intelligence: 8 Puzzle Problem

    explain problem solving agent of 8 puzzle problem

VIDEO

  1. Algebra II 8.8, Word Problem Strategy, Logical Reasoning, Logic Puzzle

  2. Explain problem solving steps

  3. AL3391

  4. How Can I Solve the 8 Puzzle Problem Using Heuristic?

  5. 8 puzzle

  6. 8 Puzzle Problem solution

COMMENTS

  1. 8 puzzle Problem using Branch And Bound

    In this puzzle solution of the 8 puzzle problem is discussed. Given a 3×3 board with 8 tiles (every tile has one number from 1 to 8) and one empty space. The objective is to place the numbers on tiles to match the final configuration using the empty space. We can slide four adjacent (left, right, above, and below) tiles into the empty space.

  2. What can be the efficient approach to solve the 8 puzzle problem?

    The 8-puzzle is a square board with 9 positions, filled by 8 numbered tiles and one gap. At any point, a tile adjacent to the gap can be moved into the gap, creating a new gap position. In other words the gap can be swapped with an adjacent (horizontally and vertically) tile. The objective in the game is to begin with an arbitrary configuration ...

  3. 8 Puzzle Algorithm

    8 Puzzle Algorithm. 8 puzzle is a very interesting problem for software developers around the world. It always has been an important subject in articles, books and become a part of course material in many universities. It is a well known problem especially in the field of Artificial Intelligence. This page is designed to tell you the very basic ...

  4. The Eight Puzzle Problem

    The Eight Puzzle, also known as the sliding tile puzzle, is a classic problem that involves a 3x3 grid with eight numbered tiles and an empty cell. The goal is to rearrange the tiles to reach a desired configuration, typically ordered from 1 to 8, with the empty cell in a specific position. To solve the Eight Puzzle Problem using recursion and ...

  5. Sai Sasank

    The 8 tiles are numbered 1 to 8. The blank can move up, down, left or right depending on it's position. Given an arbitrary initial configuration of the grid, the problem solving agent needs to find an optimal sequence of actions that lead to the goal state, if there is one. The intial state can be any possible configuration of the 3x3 grid.

  6. Solving 8-Puzzle using A* Algorithm

    Solving the sliding puzzle using a basic AI algorithm. Let's start with what I mean by an "8-Puzzle" problem. N-Puzzle or sliding puzzle is a popular puzzle that consists of N tiles where N can be 8, 15, 24, and so on. In our example N = 8. The puzzle is divided into sqrt(N+1) rows and sqrt(N+1) columns.

  7. Solving 8 puzzle problem using A* star search

    This tutorial will solve the 8 puzzle problem using the A* (star) search algorithm. We will approach the solution by first modelling the problem, building the fundamental blocks and finally applying a solver to solve the puzzle. Part 1 of this tutorial provides the introduction, the background information and the approach towards the solution ...

  8. PDF Option #1: Introduction to Informed Search Heuristics: An 8-Puzzle

    Solving the 8-Puzzle: Considering Inversions and Polarity To solve an 8-puzzle effectively, two additional terms need to be understood: inversion and polarity. As defined by Collier (2019), an inversion in an 8-puzzle context is a pair of tiles arranged in descending order instead of the correct ascending order. For example, the pairs (8, 6)

  9. 8-Puzzle Programming Assignment

    The problem. The 8-puzzle problem is a puzzle invented and popularized by Noyes Palmer Chapman in the 1870s. It is played on a 3-by-3 grid with 8 square blocks labeled 1 through 8 and a blank square. Your goal is to rearrange the blocks so that they are in order. You are permitted to slide blocks horizontally or vertically into the blank square.

  10. Recent Trends in Solving the 8-Puzzle Problem

    The 8-puzzle problem is a well-known artificial intelligence problem consisting of a 3x3 grid with 8 tiles numbered 1-8 and one blank space. The goal is to move the tiles around to achieve a specific goal configuration. This problem is often used as a test case for AI algorithms because of its small size and simple rules. It is a challenging problem because it requires a combination of search ...

  11. The 8-Puzzle

    The 8-Puzzle. The Problem. The 8-puzzle is a smaller version of the slightly better known 15-puzzle. The puzzle consists of an area divided into a grid, 3 by 3 for the 8-puzzle, 4 by 4 for the 15-puzzle. On each grid square is a tile, expect for one square which remains empty. Thus, there are eight tiles in the 8-puzzle and 15 tiles in the 15 ...

  12. 8 Puzzle Problem Explanation

    8 Puzzle Problem. The 8-puzzle is a square board with 9 positions, filled by 8 numbered tiles and one gap. At any point, a tile adjacent to the gap can be moved into the gap, creating a new gap position. In other words the gap can be swapped with an adjacent (horizontally and vertically) tile. The objective in the game is to begin with an ...

  13. Eight puzzle problem

    The 8-puzzle problem is invented and popularized by Noyes Palmer Chapman in the year 1870. It is played on a 3-by-3 grid with 8 square blocks/tiles labeled 1 through 8 and a blank square. The goal of this 8-puzzle problem is to rearrange the given blocks in the correct order. The tiles can be shifted vertically or horizontally using the empty ...

  14. Solving the 8-Puzzle with A* and SimpleAI

    The 8-Puzzle Problem. The 8-Puzzle problem is a puzzle that was invented and popularized by Noyes Palmer Chapman in the late 19th century. It consists of a 3x3 grid with eight numbered tiles and a blank space. The goal is to reach a specified goal state from a given start state by sliding the blank space up, down, left or right.

  15. Solving the 8-Puzzle Problem with AI: A Python Code Tutorial

    There are several approaches to solve the 8-puzzle problem using AI, but we'll focus on using the A* search algorithm. A* search is a heuristic search strategy that finds the shortest path between a start node and a goal node. In our case, the start node is the initial configuration of the puzzle and the goal node is the solution configuration.

  16. 8 Puzzle Problem-Artificial Intelligence-Unit-1-Problem Solving-Problem

    Unit - 1 - Problem Solving Problem Formulation - Part-IIToy Problem - 8 Puzzle ProblemInitial state, successor function, goal test and path costTransition Di...

  17. 8 puzzle problem. The 8 puzzle consists of eight…

    8 puzzle problem. The 8 puzzle consists of eight numbered, movable tiles set in a 3x3 frame. One cell of the frame is always empty thus making it possible to move an adjacent numbered tile into ...

  18. Solving an Eight Puzzle

    To get a better sense of how heuristic search works, and to see how this same process can be used to solve other kinds of problems, we are going to solve an "eight puzzle". In this puzzle, you have 8 squares in a 3x3 grid with one open square. You make moves by sliding a piece that is next to the empty square into the gap. The goal is to ...

  19. algorithm Tutorial => Solving 8-puzzle problem using A* algorithm

    Problem definition: An 8 puzzle is a simple game consisting of a 3 x 3 grid (containing 9 squares). One of the squares is empty. The object is to move to squares around into different positions and having the numbers displayed in the "goal state". Given an initial state of 8-puzzle game and a final state of to be reached, find the most cost ...

  20. 8 Puzzle Solver

    About. I first wrote an 8 puzzle solver some years in my university Artificial Intelligence class. That version was a terminal program written in Python. The purpose of that project was to learn about - and then characterize the performance of - different search algorithms and heuristic functions. Feel free to get the code on Github.

  21. N-Puzzle

    Single-Step or Burst Mode. N-Puzzle can be used in two modes. The default is Single-Step mode, which allows you to 'rewind' a search, one step at a time. This is useful for getting a better understanding of how a Search Algorithm works. The other mode is Burst Mode. Once started, Burst Mode continues running a search until the goal state has ...

  22. Solving the 8-puzzle problem using genetic programming

    The genetic programming system was successfully applied to 20 problem instances of differing difficulty, producing solutions to all 20 problems and for a majority of the problems the solutions produced solve the problem instance using the known minimum number of moves. The 8-puzzle problem is a classic artificial intelligence problem which has been well-researched. The research in this domain ...

  23. Problem Solving Agents in Artificial Intelligence

    The problem solving agent follows this four phase problem solving process: Goal Formulation: This is the first and most basic phase in problem solving. It arranges specific steps to establish a target/goal that demands some activity to reach it. AI agents are now used to formulate goals. Problem Formulation: It is one of the fundamental steps ...