import heapq
import networkx as nx
import matplotlib.pyplot as plt
def dijkstra_algorithm(graph, start_node, end_node):
"""
Implements Dijkstra's Algorithm to find the shortest path.
Returns nodes in the path and total distance.
"""
# Priority queue stores tuples of (current_distance, current_node)
queue = []
heapq.heappush(queue, (0, start_node))
# Dictionary to store the cost to reach a node (initialized to infinity)
distances = {node: float('infinity') for node in graph}
distances[start_node] = 0
# Dictionary to store the path (predecessor map)
previous_nodes = {node: None for node in graph}
while queue:
current_distance, current_node = heapq.heappop(queue)
# If we reached the target, we can stop early
if current_node == end_node:
break
# If we found a shorter path to this node already, skip
if current_distance > distances[current_node]:
continue
# Explore neighbors
for neighbor, weight in graph[current_node].items():
new_distance = current_distance + weight
# If a shorter path to neighbor is found
if new_distance < distances[neighbor]:
distances[neighbor] = new_distance
previous_nodes[neighbor] = current_node
heapq.heappush(queue, (new_distance, neighbor))
# Path reconstruction (backtracking from end_node)
path = []
current = end_node
# Check if a path actually exists
if distances[end_node] == float('infinity'):
return [], float('infinity')
while current is not None:
path.insert(0, current)
current = previous_nodes[current]
return path, distances[end_node]
def visualize_graph(graph, path=None):
"""
Visualizes the graph using NetworkX and Matplotlib.
Highlights the shortest path if provided.
"""
G = nx.DiGraph() # Directed Graph
# Build graph for NetworkX
for node, edges in graph.items():
for neighbor, weight in edges.items():
G.add_edge(node, neighbor, weight=weight)
# Define layout for node positioning
pos = nx.spring_layout(G, seed=42) # Seed for reproducible layout
plt.figure(figsize=(10, 7))
# Draw all nodes and edges (base layer)
nx.draw_networkx_nodes(G, pos, node_size=700, node_color='lightblue')
nx.draw_networkx_edges(G, pos, width=1, alpha=0.5, edge_color='gray')
nx.draw_networkx_labels(G, pos, font_size=12, font_family="sans-serif")
# Draw edge labels (weights)
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
# Highlight the path if it exists
if path and len(path) > 1:
# Create a list of edges in the path [(A,B), (B,C)...]
path_edges = list(zip(path, path[1:]))
# Draw path nodes
nx.draw_networkx_nodes(G, pos, nodelist=path, node_color='orange', node_size=700)
# Draw path edges
nx.draw_networkx_edges(G, pos, edgelist=path_edges, width=4, alpha=1, edge_color='red')
plt.title(f"Shortest Path: {' -> '.join(path)}", fontsize=15)
else:
plt.title("Graph Visualization", fontsize=15)
plt.axis('off')
plt.tight_layout()
plt.show()
# ==========================================
# Example Usage
# ==========================================
if __name__ == "__main__":
# Graph represented as an adjacency dictionary
# {Node: {Neighbor: Weight, ...}}
my_graph = {
'A': {'B': 4, 'C': 2},
'B': {'C': 5, 'D': 10},
'C': {'E': 3},
'D': {'F': 11},
'E': {'D': 4},
'F': {}
}
start = 'A'
target = 'F'
print(f"Calculating shortest path from {start} to {target}...")
path_nodes, total_dist = dijkstra_algorithm(my_graph, start, target)
if path_nodes:
print(f"Shortest Path Found: {' -> '.join(path_nodes)}")
print(f"Total Weight: {total_dist}")
visualize_graph(my_graph, path_nodes)
else:
print("No path exists.")
visualize_graph(my_graph)