Teoría de grafos, paso a paso

Curso gratuito
Primero, el cuestionario del capítulo 1

Primero, repasa el capítulo 1

Haz el cuestionario del capítulo 1: 10 preguntas, se aprueba con 7 correctas. Puedes repetirlo cuantas veces quieras.

Ripples on a Pond

Capítulo 2, lección 1 de 4

Breadth-first search: explore a graph level by level, and find shortest paths.

Narrado en inglés. Activa arriba los subtítulos en inglés, árabe, alemán, español o francés.

Lección escrita

6 min de lecturaEscrita en inglés.

A knight sits in one corner of a chessboard. What is the smallest number of moves it needs to reach the opposite corner? You could try moves at random for a long time. One simple idea answers it for certain: six.

That idea is breadth-first search (BFS). It explores a graph the way ripples spread across a pond. This lesson opens the second chapter, Exploring a Graph: how BFS works, why it finds shortest paths, and how to write it in a few lines of Python.

Ripples

Drop a stone in a pond. The first ripple reaches everything one step away, the next ripple everything two steps away, and so on. Breadth-first search does the same. Start at one vertex. First visit all of its neighbours: that is level 1. Then all of their neighbours not seen yet: level 2. And so on, until nothing new is left.

The trick that makes this work is a queue: a first in, first out line. New vertices join at the back, and the next vertex to explore always comes from the front. Because of that, every vertex of level 1 is explored before any vertex of level 2, and so on.

Run it by hand

We use the graph from the last lesson: vertices 0 to 5, with adjacency lists

0: 1 2
1: 0 2 3
2: 0 1 4
3: 1 4 5
4: 2 3
5: 3

Start at 0: mark it as seen and put it in the queue.

Take from the frontIts neighboursNew ones join the backQueue afterwards
01, 21, 21 2
10, 2, 332 3
20, 1, 443 4
31, 4, 554 5
42, 3none5
53noneempty

Every vertex was visited once, ripple by ripple: 0; then 1 and 2; then 3 and 4; and finally 5.

Breadth-first search from 0: every vertex labelled with its level.Breadth-first search from 0: every vertex labelled with its level.

Note when a vertex is marked: at the moment it joins the queue, not when it leaves. That way no vertex ever enters the queue twice.

Shortest paths

Here is why BFS matters:

The level of each vertex is exactly its distance from the start.

Why. The queue always holds vertices of at most two consecutive levels, with the lower level in front, so vertices are taken out in order of level. A vertex v first discovered from a vertex u at level k gets level k + 1, and there is a path of that length through u. There is no shorter one. If v were at distance k or less, the vertex just before it on a shortest path would be at distance at most k − 1, so (by the same argument one level down) it would have been explored before u and would have discovered v first.

To recover the actual path, remember for each vertex the one that discovered it: its parent. Follow the parents back from 5: 5, 3, 1, 0. Reversed, 0, 1, 3, 5 is a shortest path, three edges long.

Following the parents back from 5 gives a shortest path.Following the parents back from 5 gives a shortest path.

The parent edges (0-1, 0-2, 1-3, 2-4 and 3-5) form a spanning tree, the BFS tree, just like at the end of the last lesson: five edges for six vertices. The two edges left out, 1-2 and 3-4, always join vertices on the same level or on neighbouring levels. BFS never produces an edge that skips a level.

One warning: this only works when every edge counts the same. With weights, the fewest edges is not always the lightest route. In lesson 2, the direct road A-D was one edge but weight 7, while A, B, C, D weighed 3. Weighted shortest paths need Dijkstra's algorithm.

Back to the knight

Now the knight. Every square is a vertex, and two squares are joined when a knight can jump between them: 64 vertices and 168 edges. From the corner only two squares are one move away. BFS spreads from there, ripple by ripple, and the opposite corner is reached in the sixth ripple.

Knight distances from the corner: the opposite corner is on level 6.Knight distances from the corner: the opposite corner is on level 6.

So six moves is the minimum, and no clever trick can ever do better: if a five-move route existed, the opposite corner would have appeared in an earlier ripple.

The same idea finds the shortest way out of a maze: every open cell is a vertex, and the ripples flow along the corridors.

In Python

In Python, BFS takes about ten lines. A deque from the collections module gives a fast queue: it takes from the left and adds on the right, both in constant time.

from collections import deque

def bfs(adj, start):
    dist = {start: 0}
    queue = deque([start])
    while queue:
        u = queue.popleft()
        for v in adj[u]:
            if v not in dist:
                dist[v] = dist[u] + 1
                queue.append(v)
    return dist

bfs(adj, 0)  # {0: 0, 1: 1, 2: 1, 3: 2, 4: 2, 5: 3}

Breadth-first search in ten lines.Breadth-first search in ten lines.

The dist dictionary does two jobs: it records each vertex's level and it marks the vertex as seen. Every vertex enters the queue once, and every edge is looked at twice, once from each end. With an adjacency list that is linear time: about n + m steps. (A plain Python list with pop(0) would work too, but each pop(0) shifts the whole list, which can turn the search quadratic.)

Key ideas

  • Breadth-first search explores a graph level by level, using a queue, and marks each vertex when it joins the queue.
  • The level of each vertex is its distance from the start, and following the parents back gives a shortest path. The parent edges form the BFS tree.
  • It runs in linear time, O(n + m), but it only finds shortest paths when every edge counts the same.

Check yourself

1. Run BFS on the same graph, starting from vertex 5. What is the level of each vertex?

2. Why does the code check if v not in dist when adding a vertex, rather than when taking it out of the queue?

3. Would BFS find the lightest route from A to D in the weighted graph of lesson 2?

Practice on the platform

The BFS vs DFS guide compares the two searches side by side. Then open the BFS visualizer, load the same graph and run it from vertex 0. It reports each vertex with its level, reaches 5 last at distance 3, exactly as we found by hand, and builds a BFS spanning tree with 5 edges.

A continuación

Contenido del curso

0 de 20 vistas

Capítulo 1Graph Theory Foundations

Capítulo 2Exploring a GraphPrimero, el cuestionario del capítulo 1

Capítulo 3Shortest PathsPrimero, el cuestionario del capítulo 2

Capítulo 4Connecting CheaplyPrimero, el cuestionario del capítulo 3

Capítulo 5Hard ProblemsPrimero, el cuestionario del capítulo 4

Capítulo 6Network FlowsPrimero, el cuestionario del capítulo 5