Live Editable Python: Distance Vector Routing (DVR)
You can edit the code in the box below. When you click run, a pop-up will ask for your input!
# - Nodes nodes = ['X', 'Y', 'Z'] # - initial links links = [ ('X', 'Y', 1), ('X', 'Z', 5), ('Y', 'Z', 2) ] def bellman_ford(nodes, edges, source): INF = float('inf') dist = {node: INF for node in nodes} parent = {node: None for node in nodes} dist[source] = 0 for _ in range(len(nodes) - 1): updated = False for u, v, w in edges: if dist[u] != INF and dist[u] + w < dist[v]: dist[v] = dist[u] + w parent[v] = u updated = True if not updated: break for u, v, w in edges: if dist[u] != INF and dist[u] + w < dist[v]: return None, None return dist, parent def print_routing_tables(nodes, edges): for source in nodes: dist, parent = bellman_ford(nodes, edges, source) if dist is None: print(f"Negative cycle reachable from {source}") continue print(f"\n---------------------------------") print(f"Routing table for node: {source}") print("Dest\tCost\tNextHop") print("---------------------------------") for dest in nodes: if dist[dest] == float('inf'): print(f"{dest}\tINF\t-") elif dest == source: print(f"{dest}\t0\t-") else: current = dest while parent[current] is not None and parent[current] != source: current = parent[current] if parent[current] is None: next_hop = "-" else: next_hop = current print(f"{dest}\t{dist[dest]}\t{next_hop}") edges = [] for u, v, w in links: edges.append((u, v, w)) edges.append((v, u, w)) print_routing_tables(nodes, edges)
▶ Run Code
Terminal Output:
System Ready...