You are on page 1of 5

Ex.

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

def add_edge(self, u, v):


if u not in self.graph:
self.graph[u] = []
self.graph[u].append(v)
if not self.directed:
if v not in self.graph:
self.graph[v] = []
self.graph[v].append(u)

def bfs(self, start):


visited = set()
queue = [start]
visited.add(start)

while queue:
node = queue.pop(0)
print(node, end=' ')

# Check if node exists in the graph before iterating over neighbors


if node in self.graph:
for neighbor in self.graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)

def dfs(self, start):


visited = set()
self._dfs_util(start, visited)

def _dfs_util(self, node, visited):


visited.add(node)
print(node, end=' ')

# Check if node exists in the graph before iterating over neighbors


if node in self.graph:
for neighbor in self.graph[node]:
if neighbor not in visited:
self._dfs_util(neighbor, visited)

# 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 Create a set visited to keep track of visited nodes.


o Create a dictionary distances to store the shortest distances from the source node to
all other nodes, initialized to infinity.
o Create a priority queue pq to store nodes to explore, with priority based on their
tentative distances.
o Set the distance of the source node to 0 and add it to pq.
Step 2: Exploration Loop:

o While pq is not empty:


▪ Remove the node with the minimum distance from pq and add it to visited.
▪ For each neighbor of the removed node:
▪ Calculate the tentative distance to the neighbor through the removed
node.
▪ If the calculated tentative distance is less than the neighbor's current
distance in distances:
▪ Update the neighbor's distance in distances.
▪ Add the neighbor to pq with its updated distance.
Step 3: Return Results:

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

def add_edge(self, u, v, weight):


if u not in self.graph:
self.graph[u] = []
self.graph[u].append((v, weight))
if not self.directed:
if v not in self.graph:
self.graph[v] = []
self.graph[v].append((u, weight))

def dijkstra(self, start):


distances = {node: float('inf') for node in self.graph}
distances[start] = 0
pq = [(0, start)] # Priority queue of (distance, node) tuples

while pq:
(dist, current) = heapq.heappop(pq)

if dist > distances[current]:


continue # Already visited with a better distance

for neighbor, weight in self.graph[current]:


new_dist = dist + weight
if new_dist < distances[neighbor]:
distances[neighbor] = new_dist
heapq.heappush(pq, (new_dist, neighbor))

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.

You might also like