As asked
Given a weighted directed graph representing network routers and link costs, implement Dijkstra's shortest-path algorithm to compute the minimum-cost path from a source router to all other routers. This models how OSPF computes the SPF tree. Return a dictionary mapping each node to its minimum cost from the source.
Sample answer outline
Use a min-heap (priority queue) initialized with (0, source). Pop the lowest-cost node, iterate over its neighbors; if cost + edge_weight < known dist, update and push. Return the dist dictionary. Candidate should note time complexity O((V+E) log V) with a heap, discuss how OSPF uses this on the LSDB to build the forwarding table, and mention negative-weight edges are not valid for link costs.
Reference implementation (python)
import heapq
def dijkstra(graph: dict[str, list[tuple[str, int]]], src: str) -> dict[str, int]:
# graph = {'A': [('B', 10), ('C', 3)], ...}
dist = {node: float('inf') for node in graph}
dist[src] = 0
heap = [(0, src)]
while heap:
cost, u = heapq.heappop(heap)
if cost > dist[u]:
continue
for v, weight in graph[u]:
if dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
heapq.heappush(heap, (dist[v], v))
return distExpect these follow-ups
- How would you modify this to return the actual path (list of routers) not just the cost?
- Why does OSPF trigger a partial SPF recalculation rather than a full one when a leaf changes?