Professional Documents
Culture Documents
Ex 15
Ex 15
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)
while priority_queue:
current_distance, current_node = heapq.heappop(priority_queue)
# Example Usage:
if __name__ == "__main__":
graph = Graph()
start_city = "Chennai"
end_city = "Hyderabad"
OUTPUT:
The shortest distance from Chennai to Hyderabad is: 850