import heapq
class Graph:
def __init__(self):
self.nodes = {}
def add_edge(self, u, v, weight):
if u not in self.nodes:
self.nodes[u] = []
self.nodes[u].append((v, weight))
def dijkstra(self, source, destination):
# Initialize distances from source to all other nodes to infinity
distances = {node: float('inf') for node in self.nodes}
distances[source] = 0
# Initialize priority queue with source node
pq = [(0, source)]
# While there are nodes in the priority queue
while pq:
# Get the node with the smallest distance
current_distance, current_node = heapq.heappop(pq)
# If the current node is the destination, return the distance
if current_node == destination:
return current_distance
# For each neighbor of the current node
for neighbor, weight in self.nodes[current_node]:
# Calculate the new distance to the neighbor
new_distance = current_distance + weight
# If the new distance is shorter than the current distance, update the distance
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
# Push the neighbor into the priority queue with the new distance
heapq.heappush(pq, (new_distance, neighbor))
# If no path exists, return -1
return -1
# Create a graph
graph = Graph()
graph.add_edge('A', 'B', 3)
graph.add_edge('B', 'C', 4)
graph.add_edge('A', 'C', 5)
graph.add_edge('A', 'D', -1)
graph.add_edge('A', 'E', 4)
graph.add_edge('D', 'E', 2)
# Find the shortest path from A to E
shortest_path = graph.dijkstra('A', 'E')
# Print the shortest path
print(shortest_path)
Output:
6