Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

def printMatrix(mat):

for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = "
")
print()
def isSafe(x, y):
return x >= 0 and x < n and y >=
0 and y < n
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
print()
def solve(initial, empty_tile_pos,
final):
pq = priorityQueue()
cost = calculateCost(initial, final)
root = node(None,
initial,empty_tile_pos, cost, 0)
pq.push(root)
while not pq.empty():
minimum = pq.pop()
if minimum.cost == 0:
printPath(minimum)
return
for i in range(n):
new_tile_pos = [
minimum.empty_tile_pos[0] +
row[i],
minimum.empty_tile_pos[1] +
col[i], ]
if isSafe(new_tile_pos[0],
new_tile_pos[1]):
child = newNode(minimum.mat,
minimum.empty_tile_pos,
new_tile_pos,
minimum.level + 1,
minimum, final,)
pq.push(child)
initial = [ [ 1, 2, 3 ],[ 5, 6, 0 ],[ 7,
8, 4 ] ]
final = [ [ 1, 2, 3 ],[ 5, 8, 6 ],[ 0,
7, 4 ] ]
empty_tile_pos = [ 1, 2 ]
solve(initial, empty_tile_pos,
final)
Output :
123
560
ARTIFICIAL INTELLIGENCE LABORATORY

Depth First Search


DFS Algorithm
The recursive method of the Depth-First Search algorithm is implemented using
stack. A standard Depth-First Search implementation puts every vertex of the graph
into one in all 2 categories: 1) Visited 2) Not Visited. The only purpose of this
algorithm is to visit all the vertex of the graph avoiding cycles.
The DSF algorithm follows as:

1. We will start by putting any one of the graph's vertex on top of the stack.
2. After that take the top item of the stack and add it to the visited list of the
vertex.
3. Next, create a list of that adjacent node of the vertex. Add the ones which aren't
in the visited list of vertexes to the top of the stack.
4. Lastly, keep repeating steps 2 and 3 until the stack is empty.

DFS(G, u)
u.visited = true
for each v ∈ G.Adj[u]
if v.visited == false
DFS(G,v)
init() {
For each u ∈ G
u.visited = false
For each u ∈ G
DFS(G, u)
}
Program in Python
# Using a Python dictionary to act as an adjacency list
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

def dfs(visited, graph, node): #function for dfs


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')

Output
The output of the DFS code is as follow:

532487

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 in python can be implemented by using data structures like a
dictionary and lists. Breadth-First Search in tree and graph is almost the same. The only difference is
that the graph may contain cycles, so we may traverse to the same node again.

BFS Algorithm
As breadth-first search is the process of traversing each node of the graph, a standard BFS algorithm
traverses each vertex of the graph into two parts: 1) Visited 2) Not Visited. So, the purpose of the
algorithm is to visit all the vertex while avoiding cycles.
BFS starts from a node, then it checks all the nodes at distance one from the beginning node, then it
checks all the nodes at distance two, and so on. So as to recollect the nodes to be visited, BFS uses a
queue.

The steps of the algorithm work as follow:

1. Start by putting any one of the graph’s vertices at the back of the queue.
2. Now take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add those which are not within the visited list to
the rear of the queue.
4. Keep continuing steps two and three till the queue is empty.

BFS implementation in Python (Source Code)


Now, we will see how the source code of the program for implementing breadth first search in
python.

Consider the following graph which is implemented in the code below:

graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}

visited = [] # List for visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

Output
The output of the BFS code will be as follow:

537248

Traveling Salesman Problem (TSP) Implementation


# Python3 program to implement traveling salesman
# problem using naive approach.
from sys import maxsize
from itertools import permutations
V=4

# implementation of traveling Salesman Problem


def travellingSalesmanProblem(graph, s):

# store all vertex apart from source vertex


vertex = []
for i in range(V):
if i != s:
vertex.append(i)

# store minimum weight Hamiltonian Cycle


min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:

# store current Path weight(cost)


current_pathweight = 0

# compute current path weight


k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]

# update minimum
min_path = min(min_path, current_pathweight)
return min_path

# Driver Code
if __name__ == "__main__":

# matrix representation of graph


graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))

Output
80

https://www.geeksforgeeks.org/
8-puzzle-problem-using-branch-
and-bound/
https://www.studocu.com/in/document/jawaharlal-nehru-technological-university-anantapur/
computer-science-engineering/ai-lab-10-q-sol-this-is-the-artificial-intelligence-lab-manual-of-r19-
regulation-of-jntua/32449353

Write a program to implement


A* algorithm
class Node():
def __init__(self,
parent=None, position=None):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position ==
other.position
https://towardsdatascience.com/feature-selection-with-simulated-annealing-in-python-clearly-
explained-1808db14f8fa
https://visualstudiomagazine.com/articles/2021/12/01/traveling-salesman.aspx
https://medium.com/swlh/how-to-implement-simulated-annealing-algorithm-in-python-
ab196c2f56a0
https://machinelearningmastery.com/simulated-annealing-from-scratch-in-python/

You might also like