You are on page 1of 4

Ex 15: Dijkstra's Algorithm for Shortest Path

Implement any shortest path algorithm to discover the shortest route between Chennai
and Hyderabad.
ALGORITHM:
1. Create Graph Class:
a) Represent a graph with nodes (cities) and weighted edges (roads).
2. Create add_node Method:
a) Input: value - the city to be added.
b) Add the city as a node in the graph.
3. Create add_edge Method:
a) Input: from_node, to_node - the cities connected by the road, weight - the distance of
the road.
b) Add a weighted edge between the two cities.
4. Create dijkstra Function:
Input: graph - the graph containing cities and roads, start - the starting city.
Output: Dictionary with the minimum distances from the start city to all other cities.
a) Initialize a priority queue and distances dictionary.
b) Enqueue the starting city with distance 0.
c) While the priority queue is not empty:
d) Dequeue the city with the smallest distance.
e) If the distance to the current city is less than the recorded distance, update the
distance.
f) Enqueue the neighbors of the current city with updated distances.
g) Return the distances dictionary.
5. Example Usage in __main__:
a) Create an instance of the Graph class.
b) Add cities as nodes and roads as weighted edges.
c) Call dijkstra to find the shortest distances.
d) Print the shortest distance from Chennai to Hyderabad.

PROGRAM:
import heapq
from collections import defaultdict

class Graph:
def __init__(self):
self.nodes = set()
self.edges = defaultdict(list)

def add_node(self, value):


self.nodes.add(value)

def add_edge(self, from_node, to_node, weight):


self.edges[from_node].append((to_node, weight))
self.edges[to_node].append((from_node, weight))

def dijkstra(graph, start):


# Priority queue to store (distance, node) pairs
priority_queue = [(0, start)]
# Dictionary to store the minimum distance from the start to each node
distances = {node: float('infinity') for node in graph.nodes}
distances[start] = 0

while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)

if current_distance > distances[current_node]:


continue

for neighbor, weight in graph.edges[current_node]:


distance = current_distance + weight

if distance < distances[neighbor]:


distances[neighbor] = distance
heapq.heappush(priority_queue, (distance, neighbor))
return distances

# Example Usage:
if __name__ == "__main__":
graph = Graph()

# Adding cities as nodes


graph.add_node("Chennai")
graph.add_node("Hyderabad")
graph.add_node("Bangalore")
graph.add_node("Mumbai")

# Adding roads as weighted edges


graph.add_edge("Chennai", "Hyderabad", 900)
graph.add_edge("Chennai", "Bangalore", 350)
graph.add_edge("Hyderabad", "Bangalore", 500)
graph.add_edge("Hyderabad", "Mumbai", 700)
graph.add_edge("Bangalore", "Mumbai", 800)

start_city = "Chennai"
end_city = "Hyderabad"

# Finding the shortest route


shortest_distances = dijkstra(graph, start_city)

# Printing the result


print(f"The shortest distance from {start_city} to {end_city} is:
{shortest_distances[end_city]}")

OUTPUT:
The shortest distance from Chennai to Hyderabad is: 850

You might also like