Here’s the Python code to implement Dijkstra’s algorithm for the given topology:
import heapq
def dijkstra(graph, start):
# Priority queue to store (cost, node)
queue = [(0, start)]
# Distances dictionary to store the shortest path to each node
distances = {node: float('inf') for node in graph}
distances[start] = 0
# Dictionary to store the previous node in the optimal path
previous_nodes = {node: None for node in graph}
while queue:
current_distance, current_node = heapq.heappop(queue)
# Skip processing if a shorter path to current_node has been found
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
previous_nodes[neighbor] = current_node
heapq.heappush(queue, (distance, neighbor))
return distances, previous_nodes
def construct_path(previous_nodes, start, target):
path = []
while target:
path.append(target)
target = previous_nodes[target]
path.reverse()
return path
# Define the graph (topology)
graph = {
'A': {'B': 1, 'D': 3},
'B': {'A': 1, 'C': 2, 'E': 4},
'C': {'B': 2, 'F': 1},
'D': {'A': 3, 'E': 2},
'E': {'B': 4, 'D': 2, 'F': 3},
'F': {'C': 1, 'E': 3}
}
# Calculate shortest paths from node 'A'
distances, previous_nodes = dijkstra(graph, 'A')
# Print the routing table
print("Routing Table for Node A")
print("Destination | Next Hop | Cost")
for node in graph:
if node != 'A':
path = construct_path(previous_nodes, 'A', node)
next_hop = path[1] if len(path) > 1 else None
print(f" {node} | {next_hop} | {distances[node]}")
Explanation
-
Graph Definition: The
graph
dictionary defines the topology, where each key is a node and the value is another dictionary of neighbors with their respective link costs. -
Dijkstra’s Algorithm:
- A priority queue (using
heapq
) is used to keep track of nodes to be processed. distances
dictionary stores the shortest path costs from the start node to each node.previous_nodes
dictionary stores the previous node in the shortest path to reconstruct the route.
- A priority queue (using
-
Path Construction: The
construct_path
function reconstructs the path from the start node to the target node using theprevious_nodes
dictionary. -
Routing Table Output: The script calculates the shortest paths from node ‘A’ and prints the routing table with destination, next hop, and cost.
Running this code will produce the routing table for node ‘A’ based on the provided topology.