# dijkstra_visualization.py
# Requires: pip install networkx matplotlib
import heapq
import matplotlib.pyplot as plt
import networkx as nx
def dijkstra(graph, start):
"""
Compute shortest paths from `start` to all other nodes in a weighted graph.
graph: dict of dicts, e.g. graph[u][v] = weight of edge u->v
start: start node
Returns: (dist, prev)
dist: dict node -> distance from start
prev: dict node -> previous node in shortest path (for reconstruction)
"""
# Initialize distances and previous nodes
dist = {node: float('inf') for node in graph}
dist[start] = 0
prev = {node: None for node in graph}
# Priority queue of (distance, node)
pq = [(0, start)]
visited = set()
while pq:
current_dist, u = heapq.heappop(pq)
if u in visited:
continue
visited.add(u)
for v, weight in graph[u].items():
if weight < 0:
raise ValueError("Dijkstra's algorithm requires non-negative edge weights.")
alt = current_dist + weight
if alt < dist[v]:
dist[v] = alt
prev[v] = u
heapq.heappush(pq, (alt, v))
return dist, prev
def reconstruct_path(prev, start, target):
"""
Reconstruct shortest path from `start` to `target` using `prev` map.
Returns list of nodes in path, or None if unreachable.
"""
if start == target:
return [start]
if prev[target] is None:
# No path found
return None
path = []
node = target
while node is not None:
path.append(node)
node = prev[node]
path.reverse()
return path
def draw_graph(graph, path=None, title=None):
"""
Visualize the graph using networkx and matplotlib.
If `path` is given (list of nodes), it will be highlighted.
"""
G = nx.Graph() # undirected; use nx.DiGraph() for directed graphs
# Add edges with weights
for u in graph:
for v, w in graph[u].items():
G.add_edge(u, v, weight=w)
pos = nx.spring_layout(G, seed=42) # layout for nodes
# Default edge colors/widths
edge_colors = []
edge_widths = []
# Edges that are part of the shortest path
path_edges = set()
if path and len(path) > 1:
path_edges = set(zip(path, path[1:]))
for (u, v) in G.edges():
if (u, v) in path_edges or (v, u) in path_edges:
edge_colors.append("red")
edge_widths.append(3.0)
else:
edge_colors.append("lightgray")
edge_widths.append(1.0)
# Draw nodes and edges
nx.draw(
G,
pos,
with_labels=True,
node_color="lightblue",
node_size=800,
font_weight="bold",
edge_color=edge_colors,
width=edge_widths,
)
# Draw edge labels (weights)
edge_labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
if title:
plt.title(title)
plt.axis("off")
plt.tight_layout()
plt.show()
def main():
# Example weighted graph (undirected, so we add both directions)
graph = {
"A": {"B": 4, "C": 2},
"B": {"A": 4, "C": 1, "D": 5},
"C": {"A": 2, "B": 1, "D": 8, "E": 10},
"D": {"B": 5, "C": 8, "E": 2, "F": 6},
"E": {"C": 10, "D": 2, "F": 2},
"F": {"D": 6, "E": 2},
}
start = "A"
target = "F"
dist, prev = dijkstra(graph, start)
path = reconstruct_path(prev, start, target)
print("Distances from start node '{}':".format(start))
for node, d in dist.items():
print(" {} -> {}: {}".format(start, node, d))
if path is None:
print("No path found from {} to {}".format(start, target))
else:
print("\nShortest path from {} to {}: {}".format(start, target, path))
print("Total distance:", dist[target])
# Visualize graph and highlight the shortest path
draw_graph(
graph,
path=path,
title="Shortest path from {} to {}".format(start, target),
)
if __name__ == "__main__":
main()