Ai Exp 5
Ai Exp 5
Experiment No: 5
Roll No: 55 Name: Krutika pandya Div: B Batch: B1
Theory:-
BFS (Breadth-First Search): BFS is an algorithm used to traverse or search through graphs and trees.
It starts from a given node and explores all neighboring nodes at the present level before moving on
to nodes at the next level. BFS ensures that nodes are explored level by level, making it ideal for
finding the shortest path in an unweighted graph. It uses a queue to keep track of nodes to be visited.
DFS (Depth-First Search): DFS is another graph traversal algorithm that explores as far down a
branch of the graph as possible before backtracking to explore other branches. It starts from a node
and follows each path to its deepest node before backtracking and exploring new paths. DFS is often
implemented using recursion or a stack. It’s useful for tasks like finding connected components and
topological sorting.
Code-
BFS Code:
graph = {
'5': ['3', '7'],
'7': ['8'],
'4': ['8'],
'2': [],
'8': []
queue = []
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
DFS Code:
# Define the graph
graph = {
'7': ['8'],
'4': ['8'],
'2': [],
'8': []
stack = []
visited.append(node)
stack.append(node)
while stack:
# Visit the neighbors in reverse order to keep the correct DFS order
visited.append(neighbour)
stack.append(neighbour)
print("Following is the Depth-First Search:") dfs(visited, graph, '5') # Function call starting from
node '5'
Output:-