You are on page 1of 15

EXPERIMENT 7

AIM: Write a program to implement best rst search for 8-puzzle problem.

THEORY:
Best First Search (BFS) is an informed search algorithm used in ar cial intelligence
to nd the shortest path from a star ng node to a goal node. It makes use of a
priority queue and heuris c search to e ciently explore the search space.

KEY FEATURES OF THE BEST FIRST SEARCH ALGORITHM INCLUDE:


U liza on of an evalua on func on: BFS selects the most promising node among
the available nodes based on an evalua on func on. This evalua on func on helps
determine which node to explore next, considering factors such as distance to the
goal or cost.

Two lists for tracking traversal: BFS maintains two lists during the search process -
the Open list and the CLOSED list. The Open list contains the nodes that are available
for traversal at the current stage, while the CLOSED list contains nodes that have
already been traversed.

Priori za on of nodes: BFS priori zes nodes in the Open list based on their
evalua on func on values. Nodes with lower evalua on func on values, indica ng
higher promise or desirability, are explored rst.

E cient explora on of the search space: By intelligently selec ng nodes to explore


based on the evalua on func on, BFS e ciently navigates through the search space,
aiming to reach the goal node in the shortest possible path.

Overall, Best First Search is a powerful algorithm for solving various problems in
ar cial intelligence, including path nding, route op miza on, and decision making
in complex environments.

PSEUDO CODE:
Best-First-Search(Graph g, Node start) 1) Create an empty PriorityQueue

PriorityQueue pq; 2) Insert "start" in pq.

pq.insert(start)
3) Un l PriorityQueue is empty

u = PriorityQueue.DeleteMin If u is the goal


ffi
ti
ti
fi
fi
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
fi
ti
ffi
ffi
fi
fi
ti
ti
ti
ti
ti
ti
ti
ti
fi
ti
ti
Exit

Else
Foreach neighbor v of u

If v "Unvisited" Mark v "Visited" pq.insert(v)

Mark u "Examined" End procedure

SOURCE CODE:
from queue import PriorityQueue v = 14
graph = [[] for i in range(v)]

def best_ rst_search(actual_Src, target, n): visited = [False] * n


pq = PriorityQueue()
pq.put((0, actual_Src)) visited[actual_Src] = True

while pq.empty() == False: u = pq.get()[1]


print(u, end=" ")
if u == target:

break
for v, c in graph[u]:

if visited[v] == False: visited[v] = True pq.put((c, v))

print()

def addedge(x, y, cost): graph[x].append((y, cost)) graph[y].append((x, cost))

addedge(0, 1, 3) addedge(0, 2, 6) addedge(0, 3, 5) addedge(1, 4, 9) addedge(1, 5, 8)


addedge(2, 6, 12) addedge(2, 7, 14) addedge(3, 8, 7) addedge(8, 9, 5) addedge(8, 10,
6) addedge(9, 11, 1) addedge(9, 12, 10) addedge(9, 13, 2)

source = 0 target = 9

best_ rst_search(source, target, v)

OUTPUT
fi
fi
EXPERIMENT 8
AIM: Write a program to implement A* Algorithm for 8- puzzle problem.

THEORY:
The A* algorithm is a popular path nding algorithm used in ar cial intelligence and
computer science. Its key feature is its ability to e ciently nd the shortest path
from a star ng node to a goal node by intelligently selec ng nodes to explore based
on a combina on of two scores: the heuris c (h-score) and the actual cost of
reaching the node from the start (g-score).

MAIN FEATURES OF THE A* ALGORITHM INCLUDE:


Use of two lists: A* maintains two lists during the search process - the open list and
the closed list. The open list contains nodes that are currently being considered for
explora on, while the closed list contains nodes that have already been explored.

E cient node selec on: A* selects the next node to explore from the open list
based on its f-score, which is the sum of its h-score and g-score. The node with the
lowest f-score is chosen for explora on, ensuring that the algorithm priori zes nodes
that are likely to lead to the shortest path.

Tracking visited nodes: A* keeps track of visited nodes to avoid revisi ng them,
saving computa onal me and resources. Once a node is explored, it is added to the
closed list to prevent redundant explora on.

Path retracing: Each node in A* maintains a pointer to its parent node, allowing the
algorithm to retrace the shortest path from the goal node back to the start node
once the goal is reached. This allows for e cient path reconstruc on.

Overall, the A* algorithm is a powerful and widely used method for solving
path nding problems, o ering a balance between completeness and op mality by
e ciently exploring the search space while priori zing the most promising paths.

ALGORITHM:
1. Ini alize the open list 2. Ini alize the closed list

put the star ng node on the open

list (you can leave its f at zero) 3. while the open list is not empty

a) nd the node with the least f on the open list, call it "q"
ffi
ffi
fi
fi
ti
ti
ti
ti
ti
ti
ti
ti
ff
ti
fi
ti
ti
ffi
ti
ti
ffi
ti
fi
ti
fi
ti
ti
ti
ti
b) pop q o the open list

c) generate q's 8 successors and set their parents to q

d) for each successor


i) if successor is the goal, stop search
ii) else, compute both g and h for successor

successor.g = q.g + distance between successor and q

successor.h = distance from goal to successor (This can be done using many ways, we
will discuss three heuris cs- Manha an, Diagonal and Euclidean Heuris cs)

successor.f = successor.g + successor.h iii) if a node with the same posi on as

successor is in the OPEN list which has a lower f than successor, skip this successor

iV) if a node with the same posi on as successor is in the CLOSED list which has a
lower f than successor, skip this successor otherwise, add the node to the open list

end (for loop)


e) push q on the closed list end (while loop)

SOURCE CODE:
class Node:
def __init__(self, data, level, fval):

self.data = data self.level = level self.fval = fval

def generate_child(self):
x, y = self. nd(self.data, '_')
val_list = [[x, y - 1], [x, y + 1], [x - 1, y], [x + 1, y]] children = []
for i in val_list:

child = self.shu e(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 shu e(self, puz, x1, y1, x2, y2):


if x2 >= 0 and x2 < len(self.data) and y2 >= 0 and y2 < len(self.data):

temp_puz = []
temp_puz = self.copy(puz)
ffl
fi
ff
ffl
ti
ti
tt
ti
ti
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): temp = []

for i in root: t = []

for j in i: t.append(j)

temp.append(t) return temp

def nd(self, puz, x):


for i in range(0, len(self.data)):

for j in range(0, len(self.data)): if puz[i][j] == x:

return i, j class Puzzle:

def __init__(self, size): self.n = size self.open = [] self.closed = []

def accept(self): puz = []

for i in range(0, self.n): temp = input().split(" ") puz.append(temp)

return puz
def f(self, start, goal):

return self.h(start.data, goal) + start.level def h(self, start, goal):

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):
start = self.accept()
goal = self.accept()
fi
start = Node(start, 0, 0) start.fval = self.f(start, goal) self.open.append(start) while
True:

cur = self.open[0] for i in cur.data:

for j in i:
print(j, end=" ")

print("")
if self.h(cur.data, goal) == 0:

break
for i in cur.generate_child():

i.fval = self.f(i, goal)

self.open.append(i)
self.closed.append(cur)
del self.open[0]
self.open.sort(key=lambda x: x.fval, reverse=False)

puz = Puzzle(3) puz.process()

OUTPUT:
EXPERIMENT 9
AIM : Compare the di erent Search Algorithm.

THEORY:-
A search problem consists of:

• A State Space. Set of all possible states where you can be.

• A Start State. The state from where the search begins.

• A Goal State. A func on that looks at the current state returns whether or
not it is the goal state.

• The Solu on to a search problem is a sequence of ac ons, called the plan


that transforms the start state to the goal state.

• This plan is achieved through search algorithms.

Types of search algorithms: There are far too many powerful search algorithms out
there to t in a single ar cle. Instead, this ar cle will discuss six of the fundamental
search algorithms, divided into two categories, as shown below.

UNINFORMED/BLIND SEARCH:-
The uninformed search does not contain any domain knowledge such as closeness,
the loca on of the goal. It operates in a brute-force way as it only includes
informa on about how to traverse the tree and how to iden fy leaf and goal nodes.
Uninformed search applies a way in which search tree is searched without any
informa on about the search space like ini al state operators and test for the goal,
so it is also called blind search.It examines each node of the tree un l it achieves the
goal node.
ti
ti
ti
fi
ti
ti
ff
ti
ti
ti
ti
ti
ti
It can be divided into ve main types:
1. Breadth- rst search

2. Uniform cost search

3. Depth- rst search

4. Itera ve deepening depth- rst search

5. Bidirec onal Search

Each of these algorithms will have:


• 1) A problem graph, containing the start node S and the goal node G.

• 2) A strategy, describing the manner in which the graph will be traversed to


get to G.

• 3) A fringe, which is a data structure used to store all the possible states
(nodes) that you can go from the current states.

• 4) A tree, that results while traversing to the goal node.


ti
ti
fi
fi
fi
fi
• 5) A solu on plan, which the sequence of nodes from S to G.

INFORMED SEARCH:-
Informed search algorithms use domain knowledge. In an informed search, problem
informa on is available which can guide the search. Informed search strategies can
nd a solu on more e ciently than an uninformed search strategy. Informed search
is also called a Heuris c search.

A heuris c is a way which might not always be guaranteed for best solu ons but
guaranteed to nd a good solu on in reasonable me.

Informed search can solve much complex problem which could not be solved in
another way. An example of informed search algorithms is a traveling salesman
problem.

1. Greedy Search

2. A* Search

Search Heuris cs: In an informed search, a heuris c is a func on that es mates


how
close a state is to the goal state. For example – Manha an distance, Euclidean
distance, etc.

(Lesser the distance, closer the goal.) Different heuristics are used in
different informed
algorithms discussed below.
BREADTH-FIRST SEARCH:-
• 1) Breadth- rst search is the most common search strategy for traversing a
tree or graph.
This algorithm searches breadthwise in a tree or graph, so it is called breadth-
rst search.

• 2) BFS algorithm starts searching from the root node of the tree and expands
all successor node at the current level before moving to nodes of next level.

• 3) The breadth- rst search algorithm is an example of a general-graph search


algorithm.
fi
fi
ti
ti
ti
ti
fi
fi
ti
fi
ti
ffi
ti
ti
ti
tt
ti
ti
ti
• 4) Breadth- rst search implemented using FIFO queue data structure.

Advantages:
1. BFS will provide a solu on if any solu on exists.

2. If there are more than one solu ons for a given problem, then BFS will provide
the minimal solu on which requires the least number of steps.

Disadvantages:
1.It requires lots of memory since each level of the tree must be saved into memory
to expand the next level.
2.BFS needs lots of me if the solu on is far away from the root node.

Time Complexity: Time Complexity of BFS algorithm can be obtained by the number
of nodes traversed in BFS un l the shallowest Node. Where the d= depth of
shallowest solu on

Space Complexity: Space complexity of BFS algorithm is given by the Memory size of
fron er which is O(bd).
Completeness: BFS is complete, which means if the shallowest goal node is at some
nite depth, then BFS will nd a solu on.

Depth- rst search is a recursive algorithm for traversing a tree or graph data
structure.It is called the depth- rst search because it starts from the root node and
follows each path to its greatest depth node before moving to the next path.
DFS uses a stack data structure for its implementa on.The process of the DFS
algorithm is similar to the BFS algorithm.

DEPTH-FIRST SEARCH (DFS)


Depth- rst search (DFS) is an algorithm for traversing or searching tree or graph data
structures. The algorithm starts at the root node (selec ng some arbitrary node as
the root node in the case of a graph) and explores as far as possible along each
branch before backtracking. It uses last in- rst-out strategy and hence it is
implemented using a stack.
fi
ti
fi
fi
fi
ti
ti
ti
ti
fi
ti
fi
ti
ti
ti
ti
fi
ti
ti
Advantage:
1. DFS requires very less memory as it only needs to store a stack of the nodes
on the path from root node to the current node.

2. It takes less me to reach to the goal node than BFS algorithm (if it traverses
in the right path).

Disadvantage:
1. There is the possibility that many states keep re-occurring, and there is no
guarantee of nding the solu on.
2. DFS algorithm goes for deep down searching and some me it may go to the
in nite loop.

Completeness: DFS search algorithm is complete within nite state space as it will
expand Time Complexity: Time complexity of DFS will be equivalent to the node
traversed by the Where, m= maximum depth of any node and this can be much
larger than d (Shallowest Space Complexity: DFS algorithm needs to store only single
path from the root node, hence Op mal: DFS search algorithm is non-op mal, as it
may generate a large number of steps or

• Hill climbing algorithm is a local search algorithm which con nuously moves in
the direc on of increasing eleva on/value to nd the peak of the mountain or
best solu on to the problem. It terminates when it reaches a peak value
where no neighbor has a higher value.

• Hill climbing algorithm is a technique which is used for op mizing the


mathema cal problems. One of the widely discussed examples of Hill climbing
algorithm is Traveling- salesman Problem in which we need to minimize the
distance traveled by the salesman.

• It is also called greedy local search as it only looks to its good immediate
neighbour state

• In this algorithm, we don't need to maintain and handle the search tree or
graph as it only keeps a single current state.
fi
ti
ti
ti
ti
fi
ti
ti
ti
fi
fi
ti
ti
ti
ti
HILL CLIMBING ALGORITHM

Features of Hill Climbing Algorithm:


• Local Search: Hill Climbing is a local search algorithm that itera vely improves
a current solu on by making incremental changes.
• Heuris c-Based: It uses a heuris c func on to evaluate the quality of
solu ons and guides the search towards be er solu ons.
• Greedy Strategy: It follows a greedy strategy by selec ng the best neighbor at
each step, based on the heuris c evalua on.
• Memory E cient: Hill Climbing typically doesn't require extensive memory as
it focuses on the current state and its neighbors.

Advantages of Hill Climbing Algorithm:
• Simplicity: Hill Climbing is rela vely easy to implement and understand
compared to more complex algorithms.
• E ciency in Local Op ma: It can be e cient in nding local op ma or near-
op mal solu ons in problems with a smooth search space.
• Low Memory Usage: Hill Climbing can be memory-e cient since it doesn't
maintain an extensive search tree or graph.

Disadvantages of Hill Climbing Algorithm:
• Local Op ma: Hill Climbing may get stuck in local op ma, especially in
problems with rugged search spaces or mul ple peaks.
• Plateaus: It may struggle on plateaus, where the heuris c values of
neighboring solu ons are similar, leading to slow convergence.
• Limited Explora on: It focuses on improving the current solu on without
exploring a broader search space, poten ally missing global op ma.
• Sensi vity to Ini al State: The quality of the solu on found by Hill Climbing
can heavily depend on the ini al state, leading to variability in results.
ffi
ti
ti
ti
ti
ti
ffi
ti
ti
ti
ti
ti
ti
ti
ti
ti
ti
ffi
ti
ti
ti
tt
ti
fi
ti
ti
ffi
ti
ti
ti
ti
ti
ti
ti
BEST FIRST SEARCH

Features of Best First Search Algorithm:


• Informed Search: Best First Search is an informed search algorithm that uses
heuris c informa on to guide the search towards the most promising nodes.
• Heuris c-Based: It u lizes a heuris c func on to es mate the cost of reaching
the goal from each node and selects nodes with the lowest es mated cost.
• Priority Queue: BFS maintains a priority queue to priori ze nodes with lower
heuris c values, ensuring that more promising nodes are explored rst.
• Greedy Strategy: It follows a greedy strategy by priori zing nodes based on
their heuris c values, aiming to nd a solu on e ciently.

Advantages of Best First Search Algorithm:

• E ciency: Best First Search can be e cient in nding solu ons, especially in
problems with well-de ned heuris c func ons and rela vely small search
spaces.
• Op mality: When the heuris c func on is admissible (never overes mates
the actual cost), BFS guarantees nding an op mal solu on.
• Heuris c Guidance: It u lizes heuris c informa on to focus the search on
promising areas of the search space, reducing the explora on of unpromising
paths.
• Memory E ciency: BFS typically requires less memory compared to
uninformed search algorithms like breadth- rst search or depth- rst search.

Disadvantages of Best First Search Algorithm:
• Completeness: Best First Search is not guaranteed to nd a solu on if the
heuris c func on is not admissible or if the search space is in nite or too large.
• Greedy Nature: It may get stuck in local op ma or fail to explore the en re
search space thoroughly, especially in problems with mul ple peaks or
plateaus.
• Heuris c Quality: The quality of the solu on found by BFS heavily depends on
the quality of the heuris c func on, which may not always be easy to de ne
accurately.
• Complexity: In some cases, de ning an e ec ve heuris c func on that
balances between guiding the search and avoiding local op ma can be
challenging.
ffi
ti
ti
ti
ti
ti
ti
ti
ti
ffi
ti
ti
ti
fi
ti
ti
ti
ti
fi
fi
fi
ti
ti
ti
ti
ffi
ti
ti
ff
ti
ti
fi
ti
ti
ti
fi
ffi
ti
ti
fi
ti
ti
ti
ti
ti
ti
ti
ti
ti
fi
ti
ti
fi
ti
fi
ti
fi
ti
A* ALGORITHM

Features of A* Algorithm:

• Op mality: A* is an op mal search algorithm when both the heuris c


func on and the cost func on are admissible and consistent.
• Informed Search: It is an informed search algorithm that uses heuris c
informa on to guide the search towards the goal e ciently.
• Completeness: A* is complete if the search space is nite and the branching
factor is bounded.
• Memory E ciency: A* typically uses memory e ciently, especially compared
to algorithms like breadth- rst search (BFS) or depth- rst search (DFS).
Advantages of A* Algorithm:

• Op mality: A* guarantees nding an op mal solu on when the heuris c is


admissible and the cost func on is consistent.
• E ciency: It is e cient in nding solu ons, especially in problems with well-
de ned heuris c func ons and rela vely small search spaces.
• Heuris c Guidance: A* u lizes heuris c informa on to focus the search on
promising areas of the search space, reducing unnecessary explora on.
• Completeness: A* is complete if the necessary condi ons are met, ensuring
that it can nd a solu on if one exists.

Disadvantages of A* Algorithm:

• Heuris c Quality: The e ec veness of A* heavily depends on the quality of


the heuris c func on, which may not always be easy to de ne accurately.
• Memory Usage: While A* is memory-e cient compared to some algorithms,
it may s ll require signi cant memory for large search spaces or complex
problems.
• Complexity: Implemen ng A* and de ning an e ec ve heuris c func on can
be more complex than simpler algorithms like depth- rst search (DFS) or
breadth- rst search (BFS).
ffi
fi
ti
ti
ti
ti
ti
ti
ti
fi
ti
fi
ffi
ti
ffi
ti
ti
ti
fi
ti
ti
ff
ti
ti
fi
fi
fi
ti
ti
ti
ti
fi
ti
ffi
ti
ffi
ff
ti
ffi
ti
ti
fi
fi
fi
ti
fi
ti
ti
ti
ti
ti
ti
COMPARISON OF DIFFERENT SEARCH ALGORITHMS

You might also like