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.

Down the Rabbit Hole

Capítulo 2, lección 2 de 4

Depth-first search: dive as deep as you can, then back up and try the next branch.

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.

You stand at the entrance of an old garden maze with no map. How can you be sure to find the way through? More than a century ago a Frenchman named Trémaux described a method that always works: walk forward as far as you can, and at a dead end, go back to the last junction that still has a passage you have not tried, and try it.

That method is depth-first search (DFS). It dives as deep as it can and backs up only when it has to. This lesson covers how it works, the tree it builds, how it finds cycles, and how to write it in a few lines of Python.

Dive, then back up

Breadth-first search explores in ripples, level by level. Depth-first search does the opposite: it follows one path as far as it will go. When it reaches a vertex with no new neighbours, it backtracks: it steps back to the most recent vertex that still has an unexplored neighbour, and dives again from there.

To remember the way back it uses a stack: a last in, first out pile, where the most recently entered vertex is the first one to return to. Or, even simpler, recursion, where the computer keeps that stack for you: each call explores one vertex, and returning from the call is the step back.

Run it by hand

We run it on the same graph as the last two lessons, starting at 0, with the neighbours taken in the order of the adjacency lists:

0: 1 2
1: 0 2 3
2: 0 1 4
3: 1 4 5
4: 2 3
5: 3
  1. The first neighbour of 0 is 1, so we dive to 1.
  2. From 1, vertex 0 is already seen, so we go on to 2.
  3. From 2, the next new vertex is 4.
  4. From 4 we reach 3, and from 3, 5.
  5. Vertex 5 has no new neighbours, so we back up: to 3, 4, 2, 1 and finally 0. Nothing new is left anywhere.

The visit order is 0, 1, 2, 4, 3, 5. Breadth-first search gave 0, 1, 2, 3, 4, 5. A vertex finishes when the search backs up past it, and the finishing order is 5, 3, 4, 2, 1, 0. Keep finishing orders in mind: the next lesson builds a whole algorithm on them.

Depth-first search from 0: visit order 0, 1, 2, 4, 3, 5 and finish order 5, 3, 4, 2, 1, 0.Depth-first search from 0: visit order 0, 1, 2, 4, 3, 5 and finish order 5, 3, 4, 2, 1, 0.

Back edges

The edges we dived along, 0-1, 1-2, 2-4, 4-3 and 3-5, form a spanning tree, just like the BFS tree. But this one is long and thin: a single path from 0 down to 5, five levels deep, where the BFS tree was only three.

The other two edges, 0-2 and 1-3, lead from the current vertex back to a vertex that is already on the current path, an ancestor. They are called back edges. In an undirected graph, depth-first search produces no other kind of extra edge: every edge that is not in the tree joins a vertex to one of its ancestors. (If an edge led to an unvisited vertex, the search would have followed it and made it a tree edge.)

And every back edge closes a cycle: the tree path from the ancestor down to the current vertex, plus the back edge itself. The back edge from 2 to 0 closes 0, 1, 2 and back to 0.

A back edge from 2 to its ancestor 0 closes the cycle 0, 1, 2, 0.A back edge from 2 to its ancestor 0 closes the cycle 0, 1, 2, 0.

That is why depth-first search is the classic way to detect cycles: an undirected graph has a cycle exactly when DFS finds a back edge, that is, an edge to an already visited vertex other than the one it just came from.

Mazes and folders

Now the maze. Every junction and every dead end is a vertex, and the corridors between them are the edges; the maze in the video becomes a graph with 10 vertices and 11 corridors. Depth-first search walks down one corridor until it hits a dead end, backs up and tries the next one. If there is an exit, it always finds it, because it only gives up on a junction once every passage from it has been tried.

But the path it finds is not always the shortest. In the video's maze, DFS finds a way out in 48 steps while the shortest way takes 32. For the shortest way, use breadth-first search.

DFS finds a way out (48 steps), but BFS finds the shortest one (32).DFS finds a way out (48 steps), but BFS finds the shortest one (32).

Your computer searches folders the same way: it opens a folder, goes through everything inside it, including every subfolder, and only then moves on to the next folder. That depth-first order is also the order in which a file browser lists a fully expanded folder tree.

In Python

The recursive version takes five lines: mark the vertex as seen, then call the same function on every neighbour that is not seen yet.

def dfs(adj, u, seen):
    seen.add(u)
    for v in adj[u]:
        if v not in seen:
            dfs(adj, v, seen)

seen = set()
dfs(adj, 0, seen)
print(seen)  # {0, 1, 2, 3, 4, 5}

Depth-first search in five lines.Depth-first search in five lines.

Like breadth-first search, it looks at every vertex once and every edge twice, so it runs in linear time, O(n + m).

One practical warning: on a very long path, deep recursion hits Python's recursion limit (about 1,000 calls by default). An explicit stack does the same job without recursion:

def dfs_order(adj, start):
    seen, order = set(), []
    stack = [start]
    while stack:
        u = stack.pop()
        if u in seen:
            continue
        seen.add(u)
        order.append(u)
        stack.extend(reversed(adj[u]))  # reversed, so the first neighbour is popped first
    return order

dfs_order(adj, 0)  # [0, 1, 2, 4, 3, 5]

Key ideas

  • Depth-first search dives as deep as it can and backtracks at dead ends, using a stack or recursion.
  • Its tree is long and thin. In an undirected graph every non-tree edge is a back edge to an ancestor, and every back edge closes a cycle.
  • It runs in linear time and always finds a way through, but not always the shortest one.

Check yourself

1. Run DFS on the same graph starting from vertex 5, taking neighbours in list order. In what order are the vertices visited?

2. During a DFS of an undirected graph, the search at vertex u finds an edge to an already visited vertex that is not u's parent. What does that tell you?

3. You need the fewest moves from the start of a maze to the exit. Should you use DFS or BFS?

Practice on the platform

The BFS vs DFS guide works through the classic problems each search solves, and the DFS interview questions are good practice. Then open the DFS visualizer, load the same graph and run it from vertex 0. It visits 0, 1, 2, 4, 3, 5, exactly as we traced by hand, and marks each vertex as it finishes.

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