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.
The graph, stored as adjacency lists: for each vertex, the list of vertices its outgoing edges lead to, called its neighbors.
The start vertex .
The marks: for each vertex, whether it has been found. An array §14.5 of yes-or-no values indexed by vertex number, or a hash table §14.7 keyed by vertex name, answers in a few steps.
The output: the marked vertices when the search stops, and optionally a parent for each, the vertex from which it was first found. Following parents backwards from a found vertex gives a route from to that vertex.
Breadth-first search keeps its frontier in a queue, which removes items in the order they were added (first in, first out §14.14).
Mark and add to the queue.
While the queue is not empty, remove the vertex at its front; call that vertex .
For each neighbor of : if is unmarked, mark , record as the parent of , and add to the back of the queue. If is marked, do nothing.
When the queue is empty, stop.
The distance of a vertex from 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 : mark ; then, for each neighbor of in list order, if is unmarked, record as the parent of and visit . The search starts by visiting . 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 can reach. To find what can reach , 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, , , , and , and six edges: , , , , and . The adjacency lists are : ; : ; : ; : ; : . The edges and form a cycle. Run BFS from .
Mark . Queue: .
Remove . Its neighbor is unmarked: mark , parent . Its neighbor is unmarked: mark , parent . Queue: .
Remove . Its neighbor is unmarked: mark , parent . Queue: .
Remove . Its neighbor is marked: do nothing. Queue: .
Remove . Its neighbor is marked: do nothing. The queue is empty, so the search stops.
The search found , , and . It did not find : has an edge into , but no edge leads into , so no route from reaches . The cycle between and caused no repetition, because was already marked when the edge was followed. Following parents back from gives , , , so the route found is , with 2 edges; no route from to is shorter.
Now count the work. The search removed 4 vertices from the queue and followed edges, the edges leaving those 4 vertices. The edge was never followed, because was never removed. The total is units of work, each a fixed number of steps. With for the number of vertices and for the number of edges, the bound is 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: entry reads to find the same 5 edges.
DFS from , with the same lists, visits , then (the first neighbor of ), then (the neighbor of ). The only neighbor of is , which is marked, so the visit to returns, and then the visit to returns. Back at , the next neighbor is unmarked, so DFS visits , whose only neighbor is marked. DFS found the same four vertices, in the order , , , , with at most 3 visits active at once (, and ).
Stated precisely
Let be a directed graph and a vertex of . A route from to a vertex is a sequence of edges that starts at , ends at , and in which each edge starts where the previous one ended; the empty sequence is a route from to itself. Correctness: when BFS or DFS started at stops, a vertex is marked if and only if a route from to that vertex exists. Each marked vertex other than was reached along an edge from a marked vertex, so it has a route. Conversely, on any route from , 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 be the number of vertices and the number of edges. In the notation of asymptotic complexity §14.2, BFS and DFS take time, meaning at most a fixed multiple of steps, when four conditions hold.
Adjacency lists: the neighbors of a vertex can be listed in time proportional to 1 plus the number of edges leaving .
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.
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.
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 vertices are explored and, because every edge leaves exactly one vertex, at most edges are followed. Clearing the marks at the start adds steps.
A search that reaches vertices, with edges leaving them, costs a fixed multiple of 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 list entries are read and the bound is still . 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 steps, so the search costs 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 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 vertices, edges and routes from the first vertex to the last. For that is 61 vertices and 80 edges, but a search without marks arrives at the last vertex 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, bytes, about 4.6 MiB. A thread with a 2 KiB (2,048-byte) stack has room for at most levels, where means 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 others, its queue holds 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 time, but a vertex can enter the frontier once for every edge leading to it, so the frontier can grow to entries instead of .
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, and 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 time, at most a fixed multiple of the number of vertices plus the number of edges , when four conditions hold.
The graph is stored as adjacency lists, so listing the neighbors of a vertex costs time proportional to the number of edges leaving it.
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.
Adding to and removing from the queue (BFS) or stack (DFS) takes a fixed number of steps.
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 , because a vertex reachable through only one edge cannot be found without looking at that edge. An adjacency matrix raises the cost to . 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].