Algorithms and complexity · Part 15 of 36

Graphs: breadth-first, depth-first and Dijkstra

Intermediate 18 min

Model networks as graphs and find paths with BFS, DFS and Dijkstra’s shortest-path algorithm.

What you will learn

  • You can represent a graph as an adjacency list.
  • You can run BFS and DFS by hand and say what each finds.
  • You can explain Dijkstra’s algorithm and its limits.

Before this: Big-O: how cost grows with input

Graphs are everywhere

A graph is a set of nodes (vertices) connected by edges. Streets and junctions, people and friendships, web pages and links, tasks and dependencies — all graphs. Edges can be directed (one-way) and weighted (a length, a cost, a time).

The usual way to store a graph in code is an adjacency list: for each node, the list of its neighbours.

graph = {
    "A": [("B", 4), ("C", 2)],
    "B": [("D", 5)],
    "C": [("B", 1), ("D", 8)],
    "D": [],
}
A map of towns and roads with rings spreading from a start town and a highlighted shortest route

Breadth-first search (BFS)

BFS explores in rings: first all neighbours of the start, then their neighbours, and so on. It uses a queue (first in, first out). Because it reaches nodes in order of the number of edges, BFS finds shortest paths in unweighted graphs — the fewest hops.

from collections import deque
def bfs(graph, start):
    dist = {start: 0}
    queue = deque([start])
    while queue:
        node = queue.popleft()
        for nxt, _w in graph[node]:
            if nxt not in dist:
                dist[nxt] = dist[node] + 1
                queue.append(nxt)
    return dist

Cost: O(V + E) — every node and edge is handled once.

Depth-first search (DFS)

DFS goes as deep as possible along one path before backing up. It uses a stack (or recursion). It doesn't find shortest paths, but it is the tool for detecting cycles, finding connected components and ordering tasks by their dependencies (topological sort). Also O(V + E).

Dijkstra's algorithm

With weighted edges, fewest hops isn't shortest distance. Edsger Dijkstra's algorithm (published 1959) keeps a tentative distance for every node and repeatedly settles the unsettled node with the smallest distance, then relaxes its edges: if going through it is shorter, the neighbour's distance is updated.

In the graph above from A: C is settled at 2, then B at 3 (via C, not 4 directly), then D at 8 (via C–B, 3 + 5), not 10 via C–D.

With a binary-heap priority queue it costs O((V + E) log V). Its one big condition: no negative edge weights — then you need Bellman–Ford. A* adds a "distance-to-goal" estimate to Dijkstra and is what route planners and game AI use.

Try it: Graph search step by step

Run breadth-first search, depth-first search or Dijkstra from A and follow every step.

Turn on JavaScript to use this lab. Worked example:

The lab runs BFS, DFS or Dijkstra on a small weighted graph from A. Dijkstra settles A (0), C (2), B (3), E (5) and D (8); the step list explains every relaxation.

A small weighted graph with nodes A to E; the shortest path tree from A is highlighted
Dijkstra settles nodes in order of distance

Key points

  • A graph is nodes plus edges; store it as an adjacency list.
  • BFS uses a queue and finds fewest-hop paths; DFS uses a stack and finds cycles, components and topological orders. Both are O(V + E).
  • Dijkstra settles nodes in order of distance and relaxes their edges; O((V + E) log V) with a heap.
  • Dijkstra needs non-negative weights; use Bellman–Ford otherwise. A* adds a goal estimate.

Flashcards

Question: Which data structure drives BFS?
Answer: A queue (first in, first out).
Question: Which data structure drives DFS?
Answer: A stack — or recursion.
Question: What does Dijkstra’s algorithm require of the edge weights?
Answer: They must not be negative.
Question: What is the running time of BFS?
Answer: O(V + E).

Check yourself

Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.

  1. Which algorithm finds the path with the fewest edges in an unweighted graph?

    • Breadth-first search
    • Depth-first search
    • Bubble sort
    • Binary search
    Show the answer

    Breadth-first search

    BFS reaches nodes in order of their number of edges from the start.

    Source: CLRS 20.2

  2. In the lesson graph (A–B 4, A–C 2, C–B 1, B–D 5, C–D 8), what is the shortest distance from A to D?

    Show the answer

    8

    A–C–B–D = 2 + 1 + 5 = 8, shorter than A–C–D (10) or A–B–D (9).

    Source: Dijkstra 1959

  3. Why can Dijkstra fail with negative edge weights?

    • A settled node could later be reached more cheaply
    • It runs forever on every graph
    • It cannot store negative numbers
    • It only works on trees
    Show the answer

    A settled node could later be reached more cheaply

    Dijkstra assumes settled distances are final; a negative edge can make a settled distance shorter later.

    Source: CLRS 22.3

  4. Match each algorithm with its helper structure.

    Show the answer

    BFS = queue; DFS = stack; Dijkstra = priority queue

    The order in which nodes are taken out defines the algorithm.

    Source: MIT 6.006

Sources

Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.