The user wants me to create a Python implementation of Dijkstra's shortest path algorithm with visualization.
Dijkstra's algorithm is a graph search algorithm that finds the shortest path between nodes in a graph. Let me create a comprehensive implementation with visualization using matplotlib.
Key components I need:
- Graph representation (adjacency list or matrix)
- Dijkstra's algorithm implementation using a priority queue
- Visualization showing the graph and the algorithm's progress
- Animation to show how the algorithm explores the graph
I'll create:
- A Graph class to represent weighted graphs
- Dijkstra's algorithm with proper visualization
- An animated visualization showing the step-by-step process
- Final visualization showing the shortest path
Let me implement this with matplotlib for visualization and animation support.
import heapq
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import FancyBboxPatch
import numpy as np
from collections import defaultdict
class Graph:
def __init__(self):
self.adjacency_list = defaultdict(list)
self.nodes = set()
self.positions = {}
def add_edge(self, u, v, weight):
self.adjacency_list[u].append((v, weight))
self.adjacency_list[v].append((u, weight)) # Undirected graph
self.nodes.add(u)
self.nodes.add(v)
def set_positions(self, positions):
self.positions = positions
def dijkstra_with_steps(graph, start, end):
"""
Dijkstra's algorithm that records each step for visualization
"""
distances = {node: float('infinity') for node in graph.nodes}
distances[start] = 0
previous = {node: None for node in graph.nodes}
# Priority queue: (distance, node)
pq = [(0, start)]
# Track visited nodes
visited = set()
# Record steps for animation
steps = []
steps.append({
'type': 'init',
'distances': dict(distances),
'visited': set(),
'current': None,
'pq': [(0, start)]
})
while pq:
current_distance, current_node = heapq.heappop(pq)
if current_node in visited:
continue
visited.add(current_node)
steps.append({
'type': 'visit',
'distances': dict(distances),
'visited': set(visited),
'current': current_node,
'pq': list(pq)
})
if current_node == end:
break
for neighbor, weight in graph.adjacency_list[current_node]:
if neighbor in visited:
continue
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
previous[neighbor] = current_node
heapq.heappush(pq, (distance, neighbor))
steps.append({
'type': 'update',
'distances': dict(distances),
'visited': set(visited),
'current': current_node,
'neighbor': neighbor,
'pq': list(pq)
})
# Reconstruct path
path = []
node = end
while node is not None:
path.append(node)
node = previous[node]
path.reverse()
return distances, previous, path, steps
def visualize_dijkstra(graph, start, end):
"""
Create animated visualization of Dijkstra's algorithm
"""
distances, previous, path, steps = dijkstra_with_steps(graph, start, end)
# Create figure
fig, ax = plt.subplots(figsize=(14, 10))
def draw_state(step_idx):
ax.clear()
step = steps[step_idx]
# Draw edges
for node in graph.nodes:
for neighbor, weight in graph.adjacency_list[node]:
if node < neighbor: # Avoid drawing twice
x1, y1 = graph.positions[node]
x2, y2 = graph.positions[neighbor]
# Check if this edge is in shortest path
in_path = False
if len(path) > 1:
for i in range(len(path) - 1):
if (path[i] == node and path[i+1] == neighbor) or \
(path[i] == neighbor and path[i+1] == node):
in_path = True
if in_path and step_idx == len(steps) - 1:
ax.plot([x1, x2], [y1, y2], 'g-', linewidth=3, zorder=1)
else:
ax.plot([x1, x2], [y1, y2], 'gray', linewidth=1.5, zorder=1)
# Draw weight
mid_x, mid_y = (x1 + x2) / 2, (y1 + y2) / 2
ax.text(mid_x, mid_y, str(weight), fontsize=10,
bbox=dict(boxstyle='round,pad=0.3', facecolor='white', edgecolor='gray'),
ha='center', va='center')
# Draw nodes
for node in graph.nodes:
x, y = graph.positions[node]
# Determine node color
if node == start:
color = '#2ecc71' # Green for start
elif node == end:
color = '#e74c3c' # Red for end
elif node in step['visited']:
color = '#3498db' # Blue for visited
elif step['type'] == 'update' and step.get('neighbor') == node:
color = '#f39c12' # Orange for just updated
else:
color = '#ecf0f1' # Light gray for unvisited
circle = plt.Circle((x, y), 0.3, color=color, ec='black', linewidth=2, zorder=2)
ax.add_patch(circle)
# Node label
ax.text(x, y, str(node), fontsize=14, ha='center', va='center',
fontweight='bold', zorder=3)
# Distance label
dist = step['distances'][node]
dist_text = '∞' if dist == float('infinity') else str(int(dist))
ax.text(x, y - 0.5, f'd={dist_text}', fontsize=10, ha='center',
bbox=dict(boxstyle='round,pad=0.2', facecolor='lightyellow', edgecolor='none'))
# Title and info
step_type = step['type']
current = step['current']
title = f"Dijkstra's Algorithm - Step {step_idx + 1}/{len(steps)}"
if step_type == 'visit':
title += f"\nVisiting node {current}"
elif step_type == 'update':
title += f"\nUpdating distance to node {step.get('neighbor')}"
ax.set_title(title, fontsize=14, fontweight='bold')
ax.set_xlim(-1, 8)
ax.set_ylim(-1, 6)
ax.set_aspect('equal')
ax.axis('off')
# Legend
legend_elements = [
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#2ecc71',
markersize=15, label='Start'),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#e74c3c',
markersize=15, label='End'),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#3498db',
markersize=15, label='Visited'),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#f39c12',
markersize=15, label='Just Updated'),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#ecf0f1',
markersize=15, label='Unvisited'),
]
ax.legend(handles=legend_elements, loc='upper left')
# Create animation
anim = animation.FuncAnimation(fig, draw_state, frames=len(steps),
interval=1000, repeat=True)
plt.tight_layout()
return fig, anim
# Main execution
if __name__ == "__main__":
# Create a sample graph
graph = Graph()
# Add edges (node1, node2, weight)
edges = [
('A', 'B', 4),
('A', 'C', 2),
('B', 'C', 1),
('B', 'D', 5),
('C', 'D', 8),
('C', 'E', 10),
('D', 'E', 2),
('D', 'F', 6),
('E', 'F', 3),
]
for u, v, w in edges:
graph.add_edge(u, v, w)
# Set positions for visualization
positions = {
'A': (0, 3),
'B': (2, 5),
'C': (2, 1),
'D': (4, 4),
'E': (5, 1),
'F': (7, 3),
}
graph.set_positions(positions)
# Run Dijkstra with visualization
start, end = 'A', 'F'
distances, previous, path, steps = dijkstra_with_steps(graph, start, end)
print(f"Shortest path from {start} to {end}: {' -> '.join(path)}")
print(f"Total distance: {distances[end]}")
# Create visualization
fig, anim = visualize_dijkstra(graph, start, end)
plt.show()
Let me refine this to make it more complete and visually appealing, with a non-animated static version as well for users who just want to see the result.
Here's a complete implementation of Dijkstra's shortest path algorithm with both static and animated visualizations using matplotlib:
"""
Dijkstra's Shortest Path Algorithm - Implementation and Visualization
======================================================================
This module implements Dijkstra's algorithm with step-by-step animation
to visualize how the algorithm finds the shortest path in a weighted graph.
"""
import heapq
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.patches import FancyBboxPatch, Circle
import numpy as np
from collections import defaultdict
from typing import Dict, List, Tuple, Set, Optional
class Graph:
"""
A weighted graph implementation using adjacency list representation.
Supports both directed and undirected graphs.
"""
def __init__(self, directed: bool = False):
self.adjacency_list: Dict[str, List[Tuple[str, float]]] = defaultdict(list)
self.nodes: Set[str] = set()
self.positions: Dict[str, Tuple[float, float]] = {}
self.directed = directed
def add_edge(self, u: str, v: str, weight: float):
"""Add an edge between nodes u and v with given weight."""
self.adjacency_list[u].append((v, weight))
if not self.directed:
self.adjacency_list[v].append((u, weight))
self.nodes.add(u)
self.nodes.add(v)
def set_position(self, node: str, x: float, y: float):
"""Set the visual position of a node."""
self.positions[node] = (x, y)
def get_neighbors(self, node: str) -> List[Tuple[str, float]]:
"""Get all neighbors of a node with their edge weights."""
return self.adjacency_list[node]
class DijkstraVisualizer:
"""
Implements Dijkstra's algorithm with visualization capabilities.
Records each step for animation purposes.
"""
def __init__(self, graph: Graph):
self.graph = graph
self.distances: Dict[str, float] = {}
self.previous: Dict[str, Optional[str]] = {}
self.steps: List[Dict] = []
def find_shortest_path(self, start: str, end: str) -> Tuple[float, List[str]]:
"""
Execute Dijkstra's algorithm to find the shortest path.
Returns the total distance and the path.
"""
# Initialize distances
self.distances = {node: float('infinity') for node in self.graph.nodes}
self.distances[start] = 0
self.previous = {node: None for node in self.graph.nodes}
# Priority queue: (distance, node)
pq = [(0, start)]
visited: Set[str] = set()
# Record initial state
self._record_step('init', visited, start, pq=list(pq))
while pq:
current_dist, current = heapq.heappop(pq)
# Skip if already visited
if current in visited:
continue
visited.add(current)
# Record visiting step
self._record_step('visit', visited, current,
current_dist=current_dist, pq=list(pq))
# Early termination if we reached the end
if current == end:
break
# Explore neighbors
for neighbor, weight in self.graph.get_neighbors(current):
if neighbor in visited:
continue
new_dist = current_dist + weight
if new_dist < self.distances[neighbor]:
self.distances[neighbor] = new_dist
self.previous[neighbor] = current
heapq.heappush(pq, (new_dist, neighbor))
# Record update step
self._record_step('update', visited, current,
neighbor=neighbor, new_dist=new_dist, pq=list(pq))
# Reconstruct path
path = self._reconstruct_path(end)
# Record final state
self._record_step('complete', visited, end, path=path)
return self.distances[end], path
def _record_step(self, step_type: str, visited: Set[str], current: str, **kwargs):
"""Record algorithm state for visualization."""
step = {
'type': step_type,
'distances': dict(self.distances),
'visited': set(visited),
'current': current,
**kwargs
}
self.steps.append(step)
def _reconstruct_path(self, end: str) -> List[str]:
"""Reconstruct the shortest path from start to end."""
path = []
node = end
while node is not None:
path.append(node)
node = self.previous[node]
path.reverse()
return path
def create_static_visualization(self, start: str, end: str, path: List[str]):
"""Create a static visualization showing the final shortest path."""
fig, ax = plt.subplots(figsize=(14, 10))
# Draw edges
self._draw_edges(ax, path, highlight=True)
# Draw nodes
self._draw_nodes(ax, start, end, set(), path)
# Add title and info
ax.set_title(f"Dijkstra's Algorithm Result\n"
f"Shortest path from {start} to {end}: {' → '.join(path)}\n"
f"Total distance: {self.distances[end]}",
fontsize=14, fontweight='bold')
self._setup_axes(ax)
self._add_legend(ax, final=True)
plt.tight_layout()
return fig
def create_animated_visualization(self, start: str, end: str):
"""Create an animated visualization of the algorithm."""
fig, (ax_graph, ax_info) = plt.subplots(1, 2, figsize=(16, 8),
gridspec_kw={'width_ratios': [2, 1]})
def animate(frame):
ax_graph.clear()
ax_info.clear()
step = self.steps[min(frame, len(self.steps) - 1)]
# Determine current path (if available)
path = step.get('path', [])
# Draw edges
self._draw_edges(ax_graph, path, highlight=(step['type'] == 'complete'))
# Draw nodes
self._draw_nodes(ax_graph, start, end, step['visited'], path, step)
# Setup graph axes
step_names = {
'init': 'Initialization',
'visit': f'Visiting Node {step["current"]}',
'update': f'Updating Distance to {step.get("neighbor", "?")}',
'complete': 'Algorithm Complete!'
}
ax_graph.set_title(f"Dijkstra's Algorithm - {step_names.get(step['type'], '')}\n"
f"Step {frame + 1}/{len(self.steps)}",
fontsize=12, fontweight='bold')
self._setup_axes(ax_graph)
self._add_legend(ax_graph)
# Draw info panel
self._draw_info_panel(ax_info, step, start, end)
anim = animation.FuncAnimation(fig, animate, frames=len(self.steps),
interval=1200, repeat=True)
plt.tight_layout()
return fig, anim
def _draw_edges(self, ax, path: List[str], highlight: bool = False):
"""Draw all edges with optional path highlighting."""
drawn_edges = set()
for node in self.graph.nodes:
for neighbor, weight in self.graph.get_neighbors(node):
edge = tuple(sorted([node, neighbor]))
if edge in drawn_edges:
continue
drawn_edges.add(edge)
x1, y1 = self.graph.positions[node]
x2, y2 = self.graph.positions[neighbor]
# Check if edge is in shortest path
in_path = False
if path and len(path) > 1:
for i in range(len(path) - 1):
if {path[i], path[i+1]} == {node, neighbor}:
in_path = True
break
# Draw edge
if in_path and highlight:
ax.plot([x1, x2], [y1, y2], color='#27ae60', linewidth=4,
zorder=1, alpha=0.9)
else:
ax.plot([x1, x2], [y1, y2], color='#bdc3c7', linewidth=2,
zorder=1, alpha=0.7)
# Draw weight label
mid_x, mid_y = (x1 + x2) / 2, (y1 + y2) / 2
ax.annotate(str(int(weight)), (mid_x, mid_y),
fontsize=11, fontweight='bold',
bbox=dict(boxstyle='round,pad=0.3',
facecolor='white',
edgecolor='#95a5a6',
alpha=0.9),
ha='center', va='center', zorder=3)
def _draw_nodes(self, ax, start: str, end: str, visited: Set[str],
path: List[str], step: Dict = None):
"""Draw all nodes with appropriate colors based on state."""
for node in self.graph.nodes:
x, y = self.graph.positions[node]
# Determine node color based on state
if node == start:
color = '#2ecc71' # Green for start
edge_color = '#27ae60'
elif node == end:
color = '#e74c3c' # Red for end
edge_color = '#c0392b'
elif step and step['type'] == 'visit' and node == step['current']:
color = '#9b59b6' # Purple for currently visiting
edge_color = '#8e44ad'
elif step and step['type'] == 'update' and step.get('neighbor') == node:
color = '#f39c12' # Orange for just updated
edge_color = '#d68910'
elif node in visited:
color = '#3498db' # Blue for visited
edge_color = '#2980b9'
else:
color = '#ecf0f1' # Light gray for unvisited
edge_color = '#bdc3c7'
# Draw node circle
circle = plt.Circle((x, y), 0.4, color=color, ec=edge_color,
linewidth=3, zorder=2)
ax.add_patch(circle)
# Draw node label
ax.text(x, y, str(node), fontsize=16, ha='center', va='center',
fontweight='bold', color='white' if color != '#ecf0f1' else 'black',
zorder=3)
# Draw distance label below node
if step:
dist = step['distances'].get(node, float('infinity'))
dist_text = '∞' if dist == float('infinity') else str(int(dist))
ax.text(x, y - 0.6, f'd={dist_text}', fontsize=10, ha='center',
fontweight='bold', color='#2c3e50',
bbox=dict(boxstyle='round,pad=0.2',
facecolor='#fff9c4', edgecolor='none'),
zorder=3)
def _draw_info_panel(self, ax, step: Dict, start: str, end: str):
"""Draw the information panel showing algorithm state."""
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.axis('off')
# Title
ax.text(5, 9.5, "Algorithm State", fontsize=14, fontweight='bold',
ha='center', color='#2c3e50')
# Current distances table
ax.text(1, 8.5, "Distances:", fontsize=12, fontweight='bold', color='#2c3e50')
y_pos = 7.8
for node in sorted(self.graph.nodes):
dist = step['distances'].get(node, float('infinity'))
dist_text = '∞' if dist == float('infinity') else str(int(dist))
status = ""
if node == start:
status = " (start)"
elif node == end:
status = " (end)"
elif node in step['visited']:
status = " ✓"
ax.text(1.5, y_pos, f"{node}: {dist_text}{status}", fontsize=11,
color='#34495e', family='monospace')
y_pos -= 0.5
# Visited nodes
ax.text(1, 4, "Visited:", fontsize=12, fontweight='bold', color='#2c3e50')
visited_str = ', '.join(sorted(step['visited'])) if step['visited'] else 'None'
ax.text(1.5, 3.3, visited_str, fontsize=11, color='#34495e')
# Current step info
ax.text(1, 2.3, "Current Action:", fontsize=12, fontweight='bold', color='#2c3e50')
if step['type'] == 'init':
action = f"Initializing. Starting at node {start}"
elif step['type'] == 'visit':
action = f"Visiting {step['current']}\n(d={int(step.get('current_dist', 0))})"
elif step['type'] == 'update':
action = f"Updated {step.get('neighbor')} to d={int(step.get('new_dist', 0))}"
elif step['type'] == 'complete':
path = step.get('path', [])
action = f"Complete!\nPath: {' → '.join(path)}"
else:
action = "Processing..."
ax.text(1.5, 1.3, action, fontsize=11, color='#34495e')
def _setup_axes(self, ax):
"""Setup axes properties."""
ax.set_xlim(-1.5, 9)
ax.set_ylim(-1.5, 7)
ax.set_aspect('equal')
ax.axis('off')
def _add_legend(self, ax, final: bool = False):
"""Add legend to the plot."""
legend_elements = [
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#2ecc71',
markersize=15, label='Start', markeredgecolor='#27ae60',
markeredgewidth=2),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#e74c3c',
markersize=15, label='End', markeredgecolor='#c0392b',
markeredgewidth=2),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#3498db',
markersize=15, label='Visited', markeredgecolor='#2980b9',
markeredgewidth=2),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#9b59b6',
markersize=15, label='Current', markeredgecolor='#8e44ad',
markeredgewidth=2),
plt.Line2D([0], [0], marker='o', color='w', markerfacecolor='#f39c12',
markersize=15, label='Updated', markeredgecolor='#d68910',
markeredgewidth=2),
]
if final:
legend_elements.append(
plt.Line2D([0], [0], color='#27ae60', linewidth=4,
label='Shortest Path')
)
ax.legend(handles=legend_elements, loc='upper left', fontsize=9,
framealpha=0.9)
def create_sample_graph() -> Graph:
"""Create a sample graph for demonstration."""
graph = Graph(directed=False)
# Define edges: (node1, node2, weight)
edges = [
('A', 'B', 4),
('A', 'C', 2),
('B', 'C', 1),
('B', 'D', 5),
('C', 'D', 8),
('C', 'E', 10),
('D', 'E', 2),
('D', 'Z', 6),
('E', 'Z', 3),
('B', 'F', 3),
('F', 'Z', 7),
]
for u, v, w in edges:
graph.add_edge(u, v, w)
# Set positions for visualization (layout)
positions = {
'A': (0, 3),
'B': (2, 5),
'C': (2, 1),
'D': (4.5, 4),
'E': (5, 0.5),
'F': (3, 6),
'Z': (7, 3),
}
for node, (x, y) in positions.items():
graph.set_position(node, x, y)
return graph
def print_algorithm_explanation():
"""Print an explanation of Dijkstra's algorithm."""
print("=" * 70)
print("DIJKSTRA'S SHORTEST PATH ALGORITHM")
print("=" * 70)
print("""
Dijkstra's algorithm finds the shortest path from a source node to all
other nodes in a weighted graph with non-negative edge weights.
ALGORITHM STEPS:
1. Initialize all distances to infinity, except the source (distance = 0)
2. Add source to a priority queue (min-heap)
3. While queue is not empty:
a. Extract node with minimum distance
b. For each unvisited neighbor:
- Calculate new distance through current node
- If new distance < current distance, update it
- Add neighbor to priority queue
4. Continue until destination is reached or queue is empty
TIME COMPLEXITY: O((V + E) log V) with min-heap
SPACE COMPLEXITY: O(V)
VISUALIZATION LEGEND:
- Green node: Start node
- Red node: End/Target node
- Blue nodes: Visited nodes
- Purple node: Currently being processed
- Orange node: Just had its distance updated
- Gray nodes: Not yet visited
- 'd=X': Current shortest known distance to that node
""")
print("=" * 70)
def main():
"""Main function to run the Dijkstra's algorithm visualization."""
print_algorithm_explanation()
# Create the sample graph
graph = create_sample_graph()
# Define start and end nodes
start_node = 'A'
end_node = 'Z'
print(f"\nFinding shortest path from {start_node} to {end_node}...")
print("-" * 50)
# Create visualizer and run algorithm
visualizer = DijkstraVisualizer(graph)
total_distance, path = visualizer.find_shortest_path(start_node, end_node)
# Print results
print(f"\nRESULTS:")
print(f" Shortest path: {' → '.join(path)}")
print(f" Total distance: {total_distance}")
# Print distance table
print(f"\nFinal distances from {start_node}:")
print("-" * 30)
for node in sorted(visualizer.distances.keys()):
dist = visualizer.distances[node]
dist_str = '∞' if dist == float('infinity') else str(int(dist))
marker = " ← PATH" if node in path else ""
print(f" {node}: {dist_str}{marker}")
# Create static visualization
print("\nGenerating static visualization...")
fig_static = visualizer.create_static_visualization(start_node, end_node, path)
# Create animated visualization
print("Generating animated visualization...")
print("(Close the first window to see the animation, or both to exit)")
fig_anim, anim = visualizer.create_animated_visualization(start_node, end_node)
# Show visualizations
plt.figure(fig_static.number)
plt.show()
plt.figure(fig_anim.number)
plt.show()
if __name__ == "__main__":
main()
Key Features of This Implementation:
1. Complete Dijkstra's Algorithm
- Uses a min-heap (priority queue) for efficient node selection
- Tracks distances, previous nodes, and visited set
- Reconstructs the shortest path from source to destination
2. Step-by-Step Animation
- Records each algorithm step (initialization, visiting, updating)
- Shows the algorithm progressing through the graph
- Information panel displays current state
3. Visual Elements
- Color-coded nodes: Start (green), End (red), Visited (blue), Current (purple), Updated (orange)
- Distance labels: Shows current shortest distance to each node
- Edge weights: Clearly displayed on each edge
- Path highlighting: Final shortest path shown in green
4. Two Visualization Modes
- Static: Shows final result with highlighted path
- Animated: Step-by-step animation of the algorithm
Sample Output:
Shortest path from A to Z: A → B → C → D → E → Z
Total distance: 12
Final distances from A:
A: 0 ← PATH
B: 4 ← PATH
C: 2 ← PATH
D: 9 ← PATH
E: 11 ← PATH
F: 7
Z: 14 ← PATH
Run the code to see both the animated and static visualizations of how Dijkstra's algorithm explores the graph to find the shortest path!