You are on page 1of 8

4/7/2020 Solving 8-Puzzle using A* Algorithm.

- Good Audience

Solving 8-Puzzle using A* Algorithm.


Ajinkya Sonawane
Sep 16, 2018 · 7 min read

Solving sliding puzzle using 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.

Fig 1. Start and Goal con gurations of an 8-Puzzle.

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

Rules for solving the puzzle.


https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 1/8
4/7/2020 Solving 8-Puzzle using A* Algorithm. - Good Audience

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 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 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 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.

https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 2/8
4/7/2020 Solving 8-Puzzle using A* Algorithm. - Good Audience

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 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 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.

https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 3/8
4/7/2020 Solving 8-Puzzle using A* Algorithm. - Good Audience

This solves the issue of generating redundant child states, as the algorithm will expand
the node with the least f-score.

Fig 2. A* algorithm solves 8-puzzle

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).

"""
Author : Ajinkya Sonawane
"""

class Node:
def __init__(self,data,level,fval):
https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 4/8
4/7/2020 Solving 8-Puzzle using A* Algorithm. - Good Audience

""" Initialize the node with the data, level of the node and
the calculated fvalue """
self.data = data
self.level = level
self.fval = fval

def generate_child(self):
""" Generate child nodes from the given node by moving the
blank space
either in the four directions {up,down,left,right} """
x,y = self.find(self.data,'_')
""" val_list contains position values for moving the blank
space in either of
the 4 directions [up,down,left,right] respectively. """
val_list = [[x,y-1],[x,y+1],[x-1,y],[x+1,y]]
children = []
for i in val_list:
child = self.shuffle(self.data,x,y,i[0],i[1])
if child is not None:
child_node = Node(child,self.level+1,0)
children.append(child_node)
return children

def shuffle(self,puz,x1,y1,x2,y2):
""" Move the blank space in the given direction and if the
position value are out
of limits the return None """
if x2 >= 0 and x2 < len(self.data) and y2 >= 0 and y2 <
len(self.data):
temp_puz = []
temp_puz = self.copy(puz)
temp = temp_puz[x2][y2]
temp_puz[x2][y2] = temp_puz[x1][y1]
temp_puz[x1][y1] = temp
return temp_puz
else:
return None

def copy(self,root):
""" Copy function to create a similar matrix of the given
node"""
temp = []
for i in root:
t = []
for j in i:
t.append(j)
temp.append(t)
return temp

def find(self,puz,x):
""" Specifically used to find the position of the blank
space """
for i in range(0,len(self.data)):
for j in range(0,len(self.data)):
if puz[i][j] == x:
return i,j

https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 5/8
4/7/2020 Solving 8-Puzzle using A* Algorithm. - Good Audience

class Puzzle:
def __init__(self,size):
""" Initialize the puzzle size by the specified size,open
and closed lists to empty """
self.n = size
self.open = []
self.closed = []

def accept(self):
""" Accepts the puzzle from the user """
puz = []
for i in range(0,self.n):
temp = input().split(" ")
puz.append(temp)
return puz

def f(self,start,goal):
""" Heuristic Function to calculate hueristic value f(x) =
h(x) + g(x) """
return self.h(start.data,goal)+start.level

def h(self,start,goal):
""" Calculates the different between the given puzzles """
temp = 0
for i in range(0,self.n):
for j in range(0,self.n):
if start[i][j] != goal[i][j] and start[i][j] != '_':
temp += 1
return temp

def process(self):
""" Accept Start and Goal Puzzle state"""
print("Enter the start state matrix \n")
start = self.accept()
print("Enter the goal state matrix \n")
goal = self.accept()

start = Node(start,0,0)
start.fval = self.f(start,goal)
""" Put the start node in the open list"""
self.open.append(start)
print("\n\n")
while True:
cur = self.open[0]
print("")
print(" | ")
print(" | ")
print(" \\\'/ \n")
for i in cur.data:
for j in i:
print(j,end=" ")
print("")
""" If the difference between current and goal node is 0
we have reached the goal node"""
if(self.h(cur.data,goal) == 0):
break
for i in cur.generate_child():
https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 6/8
4/7/2020 Solving 8-Puzzle using A* Algorithm. - Good Audience

i.fval = self.f(i,goal)
self.open.append(i)
self.closed.append(cur)
del self.open[0]

""" sort the opne list based on f value """


self.open.sort(key = lambda x:x.fval,reverse=False)

puz = Puzzle(3)
puz.process()

Fig 3. The output of the given code.

ji k / h
https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 7/8
4/7/2020 Solving 8-Puzzle using A* Algorithm. - Good Audience

Ajinkya-Sonawane/Python
Python. Contribute to Ajinkya-Sonawane/Python development by creating
an account on GitHub.

github.com

Python AI Arti cial Intelligence Machine Learning Deep Learning

About Help Legal

https://blog.goodaudience.com/solving-8-puzzle-using-a-algorithm-7b509c331288 8/8

You might also like