import heapq
import matplotlib.pyplot as plt
import networkx as nx
# Define the weighted undirected graph as an adjacency list (bidirectional edges)
graph = {
'S': {'A': 10, 'D': 5},
'A': {'S': 10, 'B': 1, 'C': 2},
'B': {'A': 1, 'C': 3, 'D': 2, 'E': 7},
'C': {'A': 2, 'B': 3, 'E': 4},
'D': {'S': 5, 'B': 2, 'E': 1},
'E': {'B': 7, 'C': 4, 'D': 1}
}
# Node positions for nice visualization
pos = {
'S': (0, 0),
'A': (1, 2),
'B': (2.5, 3),
'C': (2, 1.5),
'D': (1, -0.5),
'E': (3, 0.5)
}
start = 'S'
goal = 'E'
# Create NetworkX graph for visualization
nx_G = nx.Graph()
for u in graph:
for v in graph[u]:
nx_G.add_edge(u, v, weight=graph[u][v])
# Dijkstra's algorithm with step-by-step visualization
def dijkstra_with_visualization(graph, nx_G, pos, start, goal):
distances = {node: float('inf') for node in graph}
distances[start] = 0
prev = {node: None for node in graph}
pq = [(0, start)]
visited = set()
plt.ion() # Turn on interactive mode for animation
fig, ax = plt.subplots(figsize=(12, 8))
edge_labels = nx.get_edge_attributes(nx_G, 'weight')
while pq:
current_dist, u = heapq.heappop(pq)
if current_dist > distances[u]:
continue
visited.add(u)
# Visualize current state
ax.clear()
node_colors = ['green' if node in visited else 'lightblue' for node in nx_G.nodes()]
nx.draw_networkx_nodes(nx_G, pos, ax=ax, node_color=node_colors, node_size=800)
nx.draw_networkx_edges(nx_G, pos, ax=ax, width=2, alpha=0.6)
nx.draw_networkx_labels(nx_G, pos, ax=ax, font_size=12, font_weight='bold')
# Distance labels on nodes (tentative distances)
dist_labels = {node: f"{distances[node]:.0f}" if distances[node] != float('inf') else '∞'
for node in nx_G.nodes()}
nx.draw_networkx_labels(nx_G, pos, labels=dist_labels, ax=ax, font_color='red', font_size=11)
# Edge weight labels
nx.draw_networkx_edge_labels(nx_G, pos, edge_labels=edge_labels, ax=ax, font_size=9)
ax.set_title(f"Dijkstra's Algorithm\n"
f"Processing: {u} (dist: {distances[u]:.0f})\n"
f"Visited: {len(visited)}/{len(graph)} nodes", fontsize=14)
ax.axis('off')
plt.tight_layout()
plt.pause(1.2)
# Relax neighboring nodes
for v, weight in graph[u].items():
alt = distances[u] + weight
if alt < distances[v]:
distances[v] = alt
prev[v] = u
heapq.heappush(pq, (alt, v))
# Final visualization: highlight shortest path to goal
ax.clear()
path = []
current = goal
while current is not None:
path.append(current)
current = prev[current]
path.reverse()
if path and path[0] == start:
path_edges = list(zip(path[:-1], path[1:]))
# All nodes green
nx.draw_networkx_nodes(nx_G, pos, ax=ax, node_color='lightgreen', node_size=800)
# Faint normal edges
nx.draw_networkx_edges(nx_G, pos, ax=ax, alpha=0.3, width=1.5)
# Highlight path edges
nx.draw_networkx_edges(nx_G, pos, ax=ax, edgelist=path_edges,
edge_color='red', width=5, style='dashed')
nx.draw_networkx_labels(nx_G, pos, ax=ax, font_size=12, font_weight='bold')
# Final distances
final_dist_labels = {node: f"{distances[node]:.0f}" for node in nx_G.nodes()}
nx.draw_networkx_labels(nx_G, pos, labels=final_dist_labels, ax=ax,
font_color='darkgreen', font_size=11)
nx.draw_networkx_edge_labels(nx_G, pos, edge_labels=edge_labels, ax=ax, font_size=9)
ax.set_title(f"Shortest Path from {start} to {goal} Found!\n"
f"Path: {' -> '.join(path)}\n"
f"Total Distance: {distances[goal]:.0f}", fontsize=14)
else:
ax.set_title(f"No path found to {goal}")
ax.axis('off')
plt.tight_layout()
plt.ioff() # Turn off interactive mode
plt.show()
# Run the visualization
print("Visualizing Dijkstra's shortest path algorithm...")
print("The animation shows the algorithm step-by-step.")
dijkstra_with_visualization(graph, nx_G, pos, start, goal)
This code implements Dijkstra's shortest path algorithm using a priority queue (binary heap via heapq) on a sample weighted undirected graph. It visualizes the process in real-time using Matplotlib and NetworkX:
- Nodes are colored light blue (unvisited), green (visited/finalized).
- Red labels on nodes show current tentative distances (∞ for unreached).
- Processing is highlighted step-by-step with pauses.
- Final frame highlights the shortest path to 'E' in red (S → D → E, distance 6) and shows all final distances.
Run the code in a Python environment with Matplotlib and NetworkX installed (pip install matplotlib networkx). The animation pauses for 1.2 seconds per step, and the final plot remains open.