Version: 0.3.38

Reachability (CP)#

The first graph problem we will explore is the problem of reachability, which checks whether there exists a path between two given vertices. This applies to any species of graph.

There are many variation around this theme however. Here are a few common ones:

  • Find all the vertices that are reachable from a single source vertex;

  • Find all the paths that connect two given vertices;

  • Find the path that connect two vertices with the minimum number of edges.

Such path finding problems are very common in real life applications. In Robotics for instance, some “path finding” algorithms often govern what route the robot takes. In Computer Science, path finding also serves model-checking, where vertices represent the internal states of the system, and path finding helps proving there is no way the system an reach an undesirable path. In games, if edges represents actions, path finding help decide whether there exist a sequence of actions for a player to win. There are applications nearly in every discipline.

Consider again for instance the “friendship graph”, we introduced earlier in Fig. 1.17. Finding a path from Denis to Kevin would reveal whether they belong to the same “community”. Here there is no such path.

In the remainder, we shall discuss the simple variant: Given a graph \(G = (V,E)\) and two vertices \(\alpha\) and \(\omega\), check whether there exists a path that connects them. For the more mathematically inclined, we shall denote the existence of such a path using \(\alpha \rightarrow \omega\), and define it as follows:

\[\begin{split}\begin{split} \forall \, (\alpha, \omega) \in V^2, \; & \alpha \rightarrow \omega \iff \\ & \exists \, (v_1, v_2, \ldots, v_n) \in V^n, \\ & \qquad \alpha = v_1 \, \land \, \omega = v_n \\ & \qquad \land \, \forall \, i \in [2, n], \; (v_{i-1}, v_i) \in E \end{split}\end{split}\]

Concretely, we extend our graph ADT with an operation has_path(source, target) which returns true if there exists a path from source to target, and false otherwise.

We can adapt the two traversal strategies we have studied for trees, namely, the breadth-first and the depth-first traversal. The only difference is that graphs may contain cycles, and that we remember which vertices we have already “visited” to avoid “looping” forever in a cycle.

As we progress through a graph we need to keep track of two things:

  • The vertices that we have discovered but not yet processed. We will name these pending vertices

  • The vertices that we have already visited (i.e., processed). We will name these the visited vertices.