Question: In this assignment, you will implement two fundamental graph searching algorithms: Depth - First Search ( DFS ) and Breadth - First Search ( BFS

In this assignment, you will implement two fundamental graph searching algorithms: Depth-First Search (DFS) and Breadth-First Search (BFS). You will use Python and Google Colab as your development environment.
Instructions
Graph Representation:
Create an undirected graph using an adjacency list. You can represent the graph as a dictionary where keys are node identifiers, and values are lists of adjacent nodes.
Implement Depth-First Search (DFS):
Write a function dfs(graph, start) that performs DFS on the graph starting from the start node.
The function should return a list of nodes in the order they are visited.
Implement Breadth-First Search (BFS):
Write a function bfs(graph, start) that performs BFS on the graph starting from the start node.
The function should return a list of nodes in the order they are visited.
Graph Visualization:
Write a function visualize_graph(graph) to visualize the graph using networkx and matplotlib.
Testing the Algorithms:
Create a sample graph and test both DFS and BFS functions.
Display the graph and the order of node visits for both algorithms.
Sample Code Structure:
import networkx as nx
import matplotlib.pyplot as plt
# Function to visualize the graph
def visualize_graph(graph):
G = nx.Graph(graph)
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightblue', edge_color='gray', node_size=2000, font_size=20)
plt.show()
# Depth-First Search (DFS) implementation
def dfs(graph, start):
visited = set()
stack =[start]
visit_order =[]
while stack:
node = stack.pop()
if node not in visited:
visited.add(node)
visit_order.append(node)
stack.extend(reversed(graph[node])) # Add adjacent nodes in reverse order for consistent traversal
return visit_order
# Breadth-First Search (BFS) implementation
def bfs(graph, start):
visited = set()
queue =[start]
visit_order =[]
while queue:
node = queue.pop(0)
if node not in visited:
visited.add(node)
visit_order.append(node)
queue.extend(graph[node]) # Add adjacent nodes
return visit_order
# Sample graph represented as an adjacency list
graph ={
'A': ['B','C'],
'B': ['A','D','E'],
'C': ['A','F'],
'D': ['B'],
'E': ['B','F'],
'F': ['C','E']
}
# Visualize the graph
visualize_graph(graph)
# Test DFS and BFS
dfs_result = dfs(graph,'A')
bfs_result = bfs(graph,'A')
print(f"DFS Visit Order: {dfs_result}")
print(f"BFS Visit Order: {bfs_result}")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!