Section 14.18

Graph reachability search

Definition

Graph reachability search is the process of finding every vertex of a graph that can be reached from a chosen start vertex by following edges. A graph is a set of vertices (items) joined by edges (links between two items); in a directed graph each edge leads one way only. The two standard algorithms §14.1 are breadth-first search (BFS), which explores vertices in order of their distance from the start, and depth-first search (DFS), which follows one route as far as it leads before backing up.

The idea

A program has 200 functions, and one of them, parse_header, changes. The functions that call parse_header directly may now behave differently, and so may the functions that call those, and so on outward. In a graph with one vertex per function and an edge from each function to each of its callers, the affected functions are exactly the vertices reachable from parse_header. The same question asks which files must be rebuilt after a source file changes, or which states a program can enter.

The search keeps two things: a mark on every vertex already found, and a frontier, the vertices found but not yet explored. Exploring a vertex means following each of its outgoing edges and adding every unmarked vertex at the far end to the frontier. The marks do two jobs. They stop the search from going round and round a cycle, a route of edges that returns to its start. And they stop it from exploring a vertex twice when two routes lead there. So the search explores each vertex at most once and follows each edge at most once.

How it works

The search uses these parts.

Breadth-first search keeps its frontier in a queue, which removes items in the order they were added (first in, first out §14.14).

  1. Mark ss and add ss to the queue.

  2. While the queue is not empty, remove the vertex at its front; call that vertex uu.

  3. For each neighbor ww of uu: if ww is unmarked, mark ww, record uu as the parent of ww, and add ww to the back of the queue. If ww is marked, do nothing.

  4. When the queue is empty, stop.

The distance of a vertex from ss is the number of edges on the shortest route to it. BFS removes vertices in order of distance, so the parent links give every found vertex a route with the fewest possible edges.

Depth-first search is usually written as a recursive function, one that calls itself. To visit a vertex uu: mark uu; then, for each neighbor ww of uu in list order, if ww is unmarked, record uu as the parent of ww and visit ww. The search starts by visiting ss. A visit returns only after everything reachable through its unmarked neighbors has been visited, so the search goes deep along one route and backs up when that route offers no unmarked vertex. The visits not yet returned sit on the call stack, the memory where a running program keeps the data of each active function call.

A forward search finds what ss can reach. To find what can reach ss, search the reversed graph, in which every edge points the other way. A call graph, the graph of which function calls which, is usually stored with an edge from each caller to the functions it calls, so the affected functions of the example above are found by searching the call graph in reverse.

Worked example

Take a directed graph with five vertices, AA, BB, CC, DD and XX, and six edges: A→BA \to B, A→CA \to C, B→DB \to D, C→DC \to D, D→BD \to B and X→DX \to D. The adjacency lists are AA: B,CB, C; BB: DD; CC: DD; DD: BB; XX: DD. The edges B→DB \to D and D→BD \to B form a cycle. Run BFS from AA.

  1. Mark AA. Queue: AA.

  2. Remove AA. Its neighbor BB is unmarked: mark BB, parent AA. Its neighbor CC is unmarked: mark CC, parent AA. Queue: B,CB, C.

  3. Remove BB. Its neighbor DD is unmarked: mark DD, parent BB. Queue: C,DC, D.

  4. Remove CC. Its neighbor DD is marked: do nothing. Queue: DD.

  5. Remove DD. Its neighbor BB is marked: do nothing. The queue is empty, so the search stops.

The search found AA, BB, CC and DD. It did not find XX: XX has an edge into DD, but no edge leads into XX, so no route from AA reaches XX. The cycle between BB and DD caused no repetition, because BB was already marked when the edge D→BD \to B was followed. Following parents back from DD gives DD, BB, AA, so the route found is A→B→DA \to B \to D, with 2 edges; no route from AA to DD is shorter.

Now count the work. The search removed 4 vertices from the queue and followed 2+1+1+1=52 + 1 + 1 + 1 = 5 edges, the edges leaving those 4 vertices. The edge X→DX \to D was never followed, because XX was never removed. The total is 4+5=94 + 5 = 9 units of work, each a fixed number of steps. With VV for the number of vertices and EE for the number of edges, the bound V+EV + E is 5+6=115 + 6 = 11 here. An adjacency matrix, a table with one yes-or-no entry for every ordered pair of vertices, would make the search read the full 5-entry row of each of the 4 removed vertices: 4×5=204 \times 5 = 20 entry reads to find the same 5 edges.

DFS from AA, with the same lists, visits AA, then BB (the first neighbor of AA), then DD (the neighbor of BB). The only neighbor of DD is BB, which is marked, so the visit to DD returns, and then the visit to BB returns. Back at AA, the next neighbor CC is unmarked, so DFS visits CC, whose only neighbor DD is marked. DFS found the same four vertices, in the order AA, BB, DD, CC, with at most 3 visits active at once (AA, BB and DD).

Stated precisely

Let GG be a directed graph and ss a vertex of GG. A route from ss to a vertex ww is a sequence of edges that starts at ss, ends at ww, and in which each edge starts where the previous one ended; the empty sequence is a route from ss to itself. Correctness: when BFS or DFS started at ss stops, a vertex is marked if and only if a route from ss to that vertex exists. Each marked vertex other than ss was reached along an edge from a marked vertex, so it has a route. Conversely, on any route from ss, the first unmarked vertex would directly follow a marked vertex; that marked vertex was explored, so the edge between them was followed and the vertex marked. Hence no route reaches an unmarked vertex.

Cost: let VV be the number of vertices and EE the number of edges. In the notation of asymptotic complexity §14.2, BFS and DFS take O(V+E)O(V + E) time, meaning at most a fixed multiple of V+EV + E steps, when four conditions hold.

  1. Adjacency lists: the neighbors of a vertex uu can be listed in time proportional to 1 plus the number of edges leaving uu.

  2. Fixed-cost marks: testing and setting a mark take a number of steps that does not grow with the graph, always for an array and on average for a hash table.

  3. Fixed-cost frontier: adding a vertex to the queue or stack, and removing one, also take a number of steps that does not grow with the graph.

  4. Mark on discovery: a vertex is marked when first found, before it enters the frontier, so it is explored at most once.

Then at most VV vertices are explored and, because every edge leaves exactly one vertex, at most EE edges are followed. Clearing the marks at the start adds VV steps.

A search that reaches VrV_r vertices, with ErE_r edges leaving them, costs a fixed multiple of Vr+ErV_r + E_r plus the cost of preparing the marks, which is nothing for a hash table that starts empty. In an undirected graph, whose edges have no direction, each edge is stored at both ends, so up to 2E2E list entries are read and the bound is still O(V+E)O(V + E). No search does better in the worst case: a vertex can be reachable through a single edge, and a search that has not looked at that edge cannot know whether the vertex is reachable.

If a condition fails, the bound changes. With an adjacency matrix, listing the neighbors of one vertex costs VV steps, so the search costs O(V2)O(V^2) however few edges there are. Without marks, the search never stops on a graph with a cycle, and on a graph without cycles it explores a vertex once per route that leads to it. Take a chain of kk diamonds: each diamond is a vertex with edges to two middle vertices, both middle vertices have an edge to a join vertex, and each join vertex starts the next diamond. The chain has 3k+13k + 1 vertices, 4k4k edges and 2k2^k routes from the first vertex to the last. For k=20k = 20 that is 61 vertices and 80 edges, but a search without marks arrives at the last vertex 220=1,048,5762^{20} = 1{,}048{,}576 times; with marks it explores the last vertex once.

Limits and common mistakes

The search is exact only for the graph as stored. If the graph lacks an edge that exists in reality, for example a call made through a function pointer (a variable that holds the address of a function) that the graph builder did not record, the search cannot find what lies behind that edge. A claim that a set of vertices is everything affected therefore has two parts: the search was correct, and the graph contains every real edge. The second part needs its own argument.

Recursive DFS keeps one call frame, the stack memory of one active call, for each vertex on the current route. On a chain of 100,000 vertices that is 100,000 frames; with an assumed 48 bytes per frame, 100,000×48=4,800,000100{,}000 \times 48 = 4{,}800{,}000 bytes, about 4.6 MiB. A thread with a 2 KiB (2,048-byte) stack has room for at most ⌊2048/48⌋=42\lfloor 2048 / 48 \rfloor = 42 levels, where ⌊x⌋\lfloor x \rfloor means xx rounded down. That is a stack overflow §4.10, although the total work is only linear. An explicit stack in ordinary memory, holding each active vertex and its position in its adjacency list, avoids it. BFS has a different weakness: started at the center of a star, a vertex with edges to all V−1V - 1 others, its queue holds V−1V - 1 vertices at once.

Only BFS gives routes with the fewest edges; DFS gives some route, often a long one. Neither gives the cheapest route when edges have different costs. Dijkstra’s algorithm, which keeps its frontier in a priority queue §14.16 ordered by the cost found so far, solves that problem when no edge cost is negative [249].

Marking a vertex when it leaves the frontier, instead of when it is found, is a common slip. The search still finds the right set in O(V+E)O(V + E) time, but a vertex can enter the frontier once for every edge leading to it, so the frontier can grow to EE entries instead of VV.

O(V+E)O(V + E) describes how the work grows, not an instruction count. For a graph given by rules instead of stored, such as all the states a program can enter, VV and EE count the reachable states §3.21 and transitions, which can be too many to store; that problem is called state explosion §3.26.

Questions answered

When do DFS and BFS require O(V+E) work?

Depth-first search (DFS) and breadth-first search (BFS) take O(V+E)O(V + E) time, at most a fixed multiple of the number of vertices VV plus the number of edges EE, when four conditions hold.

  1. The graph is stored as adjacency lists, so listing the neighbors of a vertex costs time proportional to the number of edges leaving it.

  2. Testing and setting a vertex’s mark, which records that the vertex has been found, takes a fixed number of steps: always for an array indexed by vertex number, on average for a hash table.

  3. Adding to and removing from the queue (BFS) or stack (DFS) takes a fixed number of steps.

  4. Each vertex is marked when it is first found, so it is explored at most once.

Each vertex is then explored once and each edge followed once.

In the worst case the work is also at least proportional to V+EV + E, because a vertex reachable through only one edge cannot be found without looking at that edge. An adjacency matrix raises the cost to O(V2)O(V^2). Missing marks make the search loop forever on a cycle, or take exponential time when many routes share vertices. A search that covers part of the graph costs time proportional to the vertices it reaches and the edges leaving them, plus the cost of preparing the marks. The bound concerns time only: recursive DFS can still overflow a small call stack on a deep graph.

Related entries: Directed acyclic graph (DAG) (§14.17), Cache invalidation (§14.21), Reachability (§3.21). Further reading: [249].