Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

ADVANCED ALGORITHM LAB

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

Session- 2021 to 2023


Year: - 1st year Sem: - 2nd sem
Program – M.Tech
Assignment No. - 4

Signature of the teacher Signature of the student


With Date With Date
Q1). Write a Python program to implement Breadth First Search
(BFS) algorithm. Submit it with source code and proper screenshots of
the output.

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

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:

1. In GPS navigation, it helps in finding the shortest path


available from one point to another.
2. In pathfinding algorithms
3. Cycle detection in an undirected graph
4. In minimum spanning tree
5. To build index by search index
6. In Ford-Fulkerson algorithm to find maximum flow in a
network.

Implementation

Consider the​ graph, which ​ is implemented in the code below:


CODE:

TRAVERSAL PATH>>>

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = [] # List to keep track of visited nodes.


queue = [] #Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)

while queue:
s = queue.pop(0)
print (s, end = " ")

for neighbour in graph[s]:


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

# Driver Code
bfs(visited, graph, 'A')

SHORTEST PATH>>

graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

def BFS_SP(graph, start, goal):


explored = []

# Queue for traversing the graph in the BFS


queue = [[start]]
if start == goal:
print("Same Node")
return

while queue:
path = queue.pop(0)
node = path[-1]

if node not in explored:


neighbours = graph[node]

for neighbour in neighbours:


new_path = list(path)
new_path.append(neighbour)
queue.append(new_path)

if neighbour == goal:
print("Shortest path = ", *new_path)
return
explored.append(node)

print("So sorry, but a connecting""path doesn't exist :(")


return

BFS_SP(graph, 'A', 'F')

OUTPUT:
TRAVERSAL PATH -A B C D E F

Shortest path = A C F
SCREEN SHOT:
CONCLUSION:

If you have a good understanding of core python concepts and


with the help of what you read today, you can now easily
implement breadth first search in python. I hope this article
clearly explained how this algorithm works.
Q2) Write a Python program to implement Depth First Search
(DFS) algorithm. Submit it with source code and proper
screenshots of the output.

Depth First Search (DFS)


Depth first Search or Depth first traversal is a recursive
algorithm for searching all the vertices of a graph or tree data
structure. Traversal means visiting all the nodes of a graph.

Depth First Search Algorithm

A standard DFS 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 DFS algorithm works as follows:
1)Start by putting any one of the graph's vertices on top of a
stack.
2)Take the top item of the stack 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 top of the stack.
4)Keep repeating steps 2 and 3 until the stack is empty.
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.

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' : []
}

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

def dfs(visited, graph, node):


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

dfs(visited, graph, 'A')


OUTPUT
A
B
D
E
F
C

SCREEN SHOT:
Applications
Depth-First Search Algorithm has a wide range of applications
for practical purposes. Some of them are as discussed below:

1. For finding the strongly connected components of the


graph
2. For finding the path
3. To test if the graph is bipartite
4. For detecting cycles in a graph
5. Topological Sorting
6. Solving the puzzle with only one solution.
7. Network Analysis
8. Mapping Routes
9. Scheduling a problem

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.

You might also like