Professional Documents
Culture Documents
Advanced Algorithm Lab: Paper Code:-Pgse-292
Advanced Algorithm Lab: Paper Code:-Pgse-292
BY
PROMIT KUMAR MOHANTA
PAPER CODE:- PGSE-292
ROLL NO : 10011321010
REG NO : 211000411310010
Department of Software Engineering
Maulana Abul Kalam Azad University of Technology,
Westbengal
Haringhata, Nadia 741249
A standard BFS implementation puts each vertex of the graph into one
of two categories:
1. Visited
2. Not Visited
The purpose of the algorithm is to mark each vertex as visited while
avoiding cycles.
The algorithm works as follows:
1) Start by putting any one of the graph's vertices at the back of a
queue.
2) 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 the ones which
aren't in the visited list to the back of the queue.
4) Keep repeating steps 2 and 3 until the queue is empty.
The graph might have two different disconnected parts so to make sure
that we cover every vertex, we can also run the BFS algorithm on every
node
BFS pseudocode
The pseudocode for BFS in python goes as below:
create a queue Q
mark v as visited and put v into Q
while Q is non-empty
remove the head u of Q
mark and enqueue all (unvisited) neighbors of u
APPLICATION
Breadth-first Search Algorithm has a wide range of applications
in the real-world. Some of them are as discussed below:
Implementation
TRAVERSAL PATH>>>
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
while queue:
s = queue.pop(0)
print (s, end = " ")
# Driver Code
bfs(visited, graph, 'A')
SHORTEST PATH>>
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
while queue:
path = queue.pop(0)
node = path[-1]
if neighbour == goal:
print("Shortest path = ", *new_path)
return
explored.append(node)
OUTPUT:
TRAVERSAL PATH -A B C D E F
Shortest path = A C F
SCREEN SHOT:
CONCLUSION:
Implementation
Consider the graph, which is implemented in the code
below:
Code:
# Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
SCREEN SHOT:
Applications
Depth-First Search Algorithm has a wide range of applications
for practical purposes. Some of them are as discussed below:
Conclusion
Hence, Depth-First Search is used to traverse the graph or tree.
By understanding this article, you will be able to implement
Depth-First Search in python for traversing connected
components and find the path.