| import heapq |
|
|
| def dijkstra(graph, start_node): |
| """ |
| Finds the shortest path from a start node to all other nodes in a weighted graph. |
| |
| Args: |
| graph (dict): A dictionary representing the graph. |
| Format: {node: [(neighbor, weight), ...]} |
| start_node (str): The node to start the search from. |
| |
| Returns: |
| dict: A dictionary of the shortest distance from the start node to every other node. |
| """ |
| |
| |
| |
| |
| distances = {node: float('infinity') for node in graph} |
| distances[start_node] = 0 |
| |
| |
| |
| priority_queue = [(0, start_node)] |
|
|
| |
| while priority_queue: |
| |
| current_distance, current_node = heapq.heappop(priority_queue) |
|
|
| |
| if current_distance > distances[current_node]: |
| continue |
|
|
| |
| for neighbor, weight in graph.get(current_node, []): |
| |
| |
| new_distance = current_distance + weight |
|
|
| |
| if new_distance < distances[neighbor]: |
| distances[neighbor] = new_distance |
| heapq.heappush(priority_queue, (new_distance, neighbor)) |
|
|
| return distances |
|
|
| |
|
|
| |
| |
| |
| |
| graph_map = { |
| 'A': [('B', 1), ('C', 4)], |
| 'B': [('C', 2), ('D', 5)], |
| 'C': [('D', 1)], |
| 'D': [('E', 3)], |
| 'E': [('F', 2)], |
| 'F': [('A', 5), ('G', 1)], |
| 'G': [('E', 1)] |
| } |
|
|
| start = 'A' |
| shortest_distances = dijkstra(graph_map, start) |
|
|
| print(f"Starting Node: {start}\n") |
| print("Shortest Distances to All Nodes:") |
| print("---------------------------------") |
| for node, distance in shortest_distances.items(): |
| if distance != float('infinity'): |
| print(f"Path to {node}: {distance}") |
| else: |
| print(f"Path to {node}: No path exists") |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|