Graph algorithms: BFS, DFS and Dijkstra's shortest path
Methods to explore networks and find shortest routes.
Edited by Alex C, EduAlx · Sources cited below
Explanation
BFS explores level by level (shortest path in unweighted graphs); DFS goes deep first (cycle detection, topological sort). Dijkstra's algorithm (1959) finds shortest paths with non-negative weights in O((V + E) log V) using a priority queue. A* adds a heuristic and is used in maps and games.
Example
Code
import heapq
def dijkstra(g, s):
d = {s: 0}; pq = [(0, s)]
while pq:
du, u = heapq.heappop(pq)
if du > d.get(u, float('inf')): continue
for v, w in g[u]:
if du + w < d.get(v, float('inf')):
d[v] = du + w
heapq.heappush(pq, (d[v], v))
return d
How it works, step by step
- Set distance of source to 0, others to infinity
- Pick the unvisited node with smallest distance
- Relax each outgoing edge
- Repeat until all nodes are settled
Open the interactive page with diagrams →
People behind it
- Edsger Dijkstra (1930–2002), Computer science, Netherlands: Invented the shortest-path algorithm, semaphores and structured programming. Turing Award 1972.
- Peter Hart
- Nils Nilsson
References
- E. W. Dijkstra, Numer. Math. 1959, 1, 269–271.
- P. E. Hart, N. J. Nilsson, B. Raphael, IEEE Trans. Syst. Sci. Cybern. 1968, 4, 100–107.
Textbooks
- Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein (MIT Press, 4th ed. 2022). 'CLRS', the standard algorithms text.
- Algorithms, Robert Sedgewick, Kevin Wayne (Addison-Wesley, 4th ed. 2011). Practical algorithms with Java code.
Related topics
Dynamic programmingSorting algorithms (quicksort, mergesort, heapsort)Greedy algorithms and minimum spanning treesAlgorithms and Big-O complexityString algorithms and pattern matchingTrees and binary search treesTuring machines and computabilityHash tablesP versus NPData structures: arrays, linked lists, stacks, queues