Professional Documents
Culture Documents
No : 12
Implementation of Graph Representation and Traversal Algorithms
Date :
Aim:
Write a python program for the implementation of graph representation and traversal
algorithms.
Algorithm:
BFS Algorithm:
Step 1: Create a set visited to keep track of visited nodes.
Step 2: Create a queue queue to store nodes to be visited.
Step 3: Add the starting node to queue and visited.
Step 4: While queue is not empty:
Dequeue a node from queue.
Step 5: Print the node.
Step 6: For each neighbor of the node:
If the neighbor is not in visited:
Add the neighbor to queue and visited.
DFS Algorithm:
Step 1: Create a set visited to keep track of visited nodes.
Step 2: Define a recursive function dfs_util(node, visited):
Step 3: Add node to visited.
Step 4: Print the node.
Step 5: For each neighbor of the node:
If the neighbor is not in visited:
Call dfs_util recursively on the neighbor.
Call dfs_util on the starting node.
Program:
class Graph:
def __init__(self, directed=False):
self.graph = {}
self.directed = directed
while queue:
node = queue.pop(0)
print(node, end=' ')
# Example usage
graph = Graph()
graph.add_edge('A', 'B')
graph.add_edge('A', 'C')
graph.add_edge('B', 'D')
graph.add_edge('C', 'D')
graph.add_edge('D', 'E')
print("BFS Traversal:")
graph.bfs('A')
print("\nDFS Traversal:")
graph.dfs('A')
Result:
Thus the Python program for the implementation of graph representation and traversal
algorithms was executed and verified successfully.
Ex. No : 13 Implementation of single source shortest path algorithm
Date : (Dijkstra's algorithm)
Aim:
Write a Python program for the implementation of single source shortest path algorithm.
Algorithm:
Step 1: Initialization:
o Return the distances dictionary containing the shortest distances from the source node
to all other nodes.
Program:
import heapq
class Graph:
def __init__(self, directed=False):
self.graph = {}
self.directed = directed
while pq:
(dist, current) = heapq.heappop(pq)
return distances
# Example usage
graph = Graph()
graph.add_edge('A', 'B', 5)
graph.add_edge('A', 'C', 2)
graph.add_edge('B', 'D', 1)
graph.add_edge('C', 'D', 4)
graph.add_edge('D', 'E', 3)
distances = graph.dijkstra('A')
print("Shortest distances from A:", distances)
Result:
Thus, the Python program for implementing a single source shortest path algorithm (Dijkstra's
algorithm) was executed and verified successfully.