Study Atlas › Computer Science › Algorithms

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

Navigation apps compute fastest routes on road graphs using Dijkstra/A* variants.

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

  1. Set distance of source to 0, others to infinity
  2. Pick the unvisited node with smallest distance
  3. Relax each outgoing edge
  4. Repeat until all nodes are settled

Open the interactive page with diagrams →

People behind it

References

  1. E. W. Dijkstra, Numer. Math. 1959, 1, 269–271.
  2. P. E. Hart, N. J. Nilsson, B. Raphael, IEEE Trans. Syst. Sci. Cybern. 1968, 4, 100–107.

Textbooks

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