Pattern visualizer
Shortest Path in Unweighted Graph
When every edge costs the same, distance from the source is just how many BFS layers deep a node sits — so plain level-by-level BFS, not Dijkstra, already finds the shortest path. Track one distance per node (unknown until first discovered) and one parent pointer to rebuild the actual route afterward. The moment the destination is pulled off the queue, its distance is final and the answer is that number; nothing later in the queue can ever produce a shorter route to it. Animated on: n = 6, edges = [[0,1],[0,2],[1,3],[2,3],[3,4],[4,5]], source = 0, destination = 5 — shortest distance?.
BFS: with every edge worth 1 step, the first visit to a node IS its shortest distance
Undirected graph, unit edge weights
6 nodes, every edge worth 1 step. Find node 0's shortest distance to node 5. With every edge the same length, BFS visits nodes in strict order of distance from the source, so the first time 5 comes out of the queue, that distance is final.
1FUNCTION shortestPath(n, edges, source, dest):2 BUILD adjacency list FROM edges3 FOR c FROM 0 TO n - 14 dist[c] <- -15 dist[source] <- 06 queue <- [source]7 WHILE queue NOT EMPTY8 u <- REMOVE FIRST FROM queue9 IF u = dest10 RETURN dist[u]11 FOR EACH v IN adjacency[u]12 IF dist[v] = -113 dist[v] <- dist[u] + 114 APPEND v TO queue15 RETURN dist[dest]
← / → step · space play · Home restart