Find the shortest path in a weighted graph using a greedy approach.
Efficient, optimal, and widely used in navigation and networks.
Dijkstra's Algorithm computes the shortest path from a starting node to all other nodes in a weighted graph with non-negative edge weights. It is fundamental in computer science and is used in GPS, network routing, and many pathfinding applications.
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = [(0, start)]
while queue:
curr_dist, curr_node = heapq.heappop(queue)
if curr_dist > distances[curr_node]:
continue
for neighbor, weight in graph[curr_node]:
distance = curr_dist + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(queue, (distance, neighbor))
return distances
# Example usage:
graph = {
'A': [('B', 2), ('C', 5)],
'B': [('A', 2), ('C', 1), ('D', 4)],
'C': [('A', 5), ('B', 1), ('D', 1)],
'D': [('B', 4), ('C', 1)]
}
print(dijkstra(graph, 'A')) # {'A': 0, 'B': 2, 'C': 3, 'D': 4}