5.3 Paths in a Graph A directed graph is simple if there is no more than one edge with a given start and end vertices. We define a path in such a graph as a sequence of vertices where each next vertex can be reached by an edge from the preceding one. A path is acyclic if no vertex in it is repeated. We want a function which, given a graph G and a vertex V in it, will list all acyclic paths in G starting from V. The first decision to make, as always, is the representation of the objects. We shall represent a graph in the format
The shortest solution of the problem is:
With the graph in Fig. 5.1 and the initial vertex E , our function results in:
Let us explain how we came to this solution. As often happens, it is not an original problem but its generalization that admits a straightforward recursive definition. In our case we make two generalizations: first, instead of a single starting vertex V, we consider a list of vertices Vlist , asking for the set of paths which can start with any vertex from Vlist. Second, we allow an arbitrary prefix P of the paths we compute. Thus
The idea of the algorithm is to remove from the graph the records for those vertices which have already appeared in the path. In this way we guarantee that there will be no repeated entries in the paths we construct. In the left side of sentence 1 we see a pattern which finds the first vertex sV for which continuation is still possible because there is a record for it in the graph. Then the set we want will consist of two subsets for which we have written two parallel recursive calls of Paths : in the first we add sV to eP , e.Next becomes Vlist, and the record for sV is eliminated; in the second, we look for other vertices in Vlistwith the unaltered graph G. When there are no possible continuations, we give out the path P. From the viewpoint of efficiency, however, this algorithm is faulty, because at each recursive step of Pathsone extra copy of the graph (or what remains of the graph) is made. This is corrected in the following program:
The graph is taken from the argument of Pathsand kept buried under 'graph' . Each time we want a continuation for a vertex, we use the function Next , which copies only the pertinent part of the
graph definition. We therefore have to check at each recursive step of Path that the candidate vertex does not appear in the path (sentence 1). |