0% found this document useful (0 votes)
6 views

Ai 1 To 4 Final With Algo

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Ai 1 To 4 Final With Algo

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

ARPIT 22862

EXPERIMENT NO: 1
AIM: Write a Program to Implement Breadth First Search using Python.
Introduction: Breadth-First Search (BFS) is an algorithm used for traversing graphs or trees.
Traversing means visiting each node of the graph. Breadth-First Search is a recursive algorithm to
search all the vertices of a graph or a tree. BFS algorithm can be used as a traversal method to find
all the neighbouring nodes. Most torrent clients, such as BitTorrent, uTorrent, etc. employ this
process to find "seeds" and "peers" in the network
Algorithm:
Step 1: Put the initial node on a list START.
Step 2: If (START=EMPTY) or (START = GOAL) terminal search.
Step 3: Remove the first node from START call this node ‘a’.
Step 4: If (a=GOAL) terminate search with success.
Step 5: Else if node a has successors generate all of them & put them at tail of START i.e. in
queue.
Step 6: go to Step2.
Problem Statement:

Figure:-1 Given graph

1

ARPIT 22862
Program:
# Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict
# This class represents a directed graph
# using adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (max(self.graph) + 1)
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print (s, end = " ")
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
2

ARPIT 22862
# visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
if __name__ == '__main__':
# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(1, 3)
g.addEdge(1, 4)
g.addEdge(3, 4)
g.addEdge(4, 1)
g.addEdge(4, 5)
g.addEdge(4, 8)
g.addEdge(5, 1)
g.addEdge(8, 8)
print ("Following is Breadth First Traversal"
" (starting from vertex 4)")
g.BFS(4)
OUTPUT:
Following is Breadth First Traversal (Starting from vertex 4)
41583

3

ARPIT 22862

EXPERIMENT NO: 2
AIM : Write a program to implement Depth First Search using Python.
Introduction:
The Depth-First Search is a recursive algorithm that uses the concept of backtracking. It involves
thorough searches of all the nodes by going ahead if potential, else by backtracking. Depth-first
search (DFS) is an algorithm for traversing or searching tree or graph data structures. The
algorithm starts at the root node (selecting some arbitrary node as the root node in the case of a
graph) and explores as far as possible along each branch before backtracking.
Algorithm:
Step 1: Put the initial node on a list START.
Step 2: If (START=EMPTY) or (START=GOAL) terminated search.
Step 3: Remove the first node from START, call this node ‘a’.
Step 4: If (a=GOAL) terminate search with success.
Step 5: Else if node a has successors, generate all of them & put them at the begging of Start that
in stack
Step 6: Go to step 2.
Problem Statement:

Figure:-1 Given graph

4

ARPIT 22862

Program:
# Python3 Program to print BFS traversal
# from a given source vertex. BFS(int s)
# traverses vertices reachable from s.
from collections import defaultdict
# This class represents a directed graph
# using adjacency list representation
class Graph:
# Constructor
def __init__(self):
# Default dictionary to store graph
self.graph = defaultdict(list)
# Function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (max(self.graph) + 1)
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
visited[s] = True

while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print(s, end=" ")

5

ARPIT 22862
# Get all adjacent vertices of the
# dequeued vertex s.
# If an adjacent has not been visited,
# then mark it visited and enqueue it
for i in self.graph[s]:
if not visited[i]:
queue.append(i)
visited[i] = True
# Driver code
if __name__ == '__main__':
# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(2, 3)
g.addEdge(2, 4)
g.addEdge(3, 4)
g.addEdge(3, 5)
g.addEdge(4, 2)
g.addEdge(5, 5)
print("Following is Breadth First Traversal"
" (starting from vertex 3)")
g.BFS(3)

OUTPUT:
Following is Depth First Traversal (Starting from vertex 3)
3452

6

ARPIT 22862
EXPERIMENT NO: 3

AIM:Write a program to implement Best First Search Using Python.


Input:
Best First Search is a heuristic search algorithm that explores a graph by expanding the most
promising node first, according to a specified evaluation function. It continuously selects nodes
based on their estimated cost to reach the goal, typically using a priority queue. BFS is suitable
for finding paths in graphs and optimization problems where informed decision-making is
crucial.
Algorithm:
Step 1: Put the initial node on a list START.
Step 2: if (START=EMPTY) or (START=GOAL) terminate search.
Step 3: Remove the first node from START and call this node as ‘a’.
Step 4: If (a=GOAL) terminate search & display search successfully.
Step 5: IF Node a has successors then generate all of them, Find out how for they are from the
Goal node. Sort all the children generated so fro by the remaining distance and add them to tail
of start.
Step 6: Go to Step 2.
Problem Statement:

Figure 1: Given graph

7

ARPIT 22862
Program:
from queue import PriorityQueue
v = 14
graph = [[] for i in range(v)]
# Function For Implementing Best First Search
# Gives output path having lowest cost
def best_first_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]
# Displaying the path having lowest cost
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()
# Function for adding edges to graph
def addedge(x, y, cost):
graph[x].append((y, cost))
graph[y].append((x, cost))
# The nodes shown in above example(by alphabets) are
# implemented using integers addedge(x, y, cost);
addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(0, 3, 5)
addedge(1, 4, 9)
addedge(1, 5, 8)
8

ARPIT 22862
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_first_search(source, target, v)
OUTPUT:
Following is Best First Search (Starting from Source)
013289

9

ARPIT 22862
EXPERIMENT NO: 4
AIM : Write a program to implement Hill Climbing Algorithm Using Python.
Introduction:
Hill climbing is a simple optimization algorithm used in Artificial Intelligence (AI) to find the
best possible solution for a given problem. It belongs to the family of local search algorithms and
is often used in optimization problems where the goal is to find the best solution from a set of
possible solutions.
Algorithm:
Step 1: Put the initial node on a list START.
Step 2: If (START=Empty) or (START=GOAL) terminate search.
Step 3: Remove the first node from START and call this node as ‘a’.
Step 4: If (a=GOAL) terminate search and display search successful.
Step 5: If node a has any successor, generate all of them. Find their distance from the GOAL
node them by remaining distance from the GOAL & add them to beginning of START.
Step 6: Go to step 2.
Problem Statement:

Figure 1: Given graph

10

ARPIT 22862

Program:
import random
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []
for i in range(len(tsp)):
randomCity = cities[random.randint(0, len(cities) - 1)]
solution.append(randomCity)
cities.remove(randomCity)
return solution
def routeLength(tsp, solution):
routeLength = 0
for i in range(len(solution)):
routeLength += tsp[solution[i - 1]][solution[i]]
return routeLength
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
for j in range(i + 1, len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
neighbours.append(neighbour)
return neighbours
def getBestNeighbour(tsp, neighbours):
bestRouteLength = routeLength(tsp, neighbours[0])
bestNeighbour = neighbours[0]
for neighbour in neighbours:
currentRouteLength = routeLength(tsp, neighbour)
if currentRouteLength < bestRouteLength:
bestRouteLength = currentRouteLength

11

ARPIT 22862
bestNeighbour = neighbour
return bestNeighbour, bestRouteLength
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
currentRouteLength = routeLength(tsp, currentSolution)
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)

while bestNeighbourRouteLength < currentRouteLength:


currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
bestNeighbour, bestNeighbourRouteLength = getBestNeighbour(tsp, neighbours)

return currentSolution, currentRouteLength


def main():
tsp = [
[0, 400, 500, 300],
[400, 0, 300, 500],
[500, 300, 0, 400],
[300, 500, 400, 0] ]
print(hillClimbing(tsp))
if __name__ == "__main__":
main()
OUTPUT:
([0,1,2,3], 1400)

12

You might also like