How to Design Programs: An Introduction to Computing and Programming
Algorithms that Backtrack
Solving problems does not always proceed on a direct route to the goal. Sometimes we make progress by pursuing one
approach only to discover that we are stuck because we took a wrong turn. In those cases, we backtrack in our
exploration and take a different turn at some branch, in the hope that it leads us to a solution. Algorithms can proceed
like that. In the first subsection, we deal with an algorithm that can help us traverse a graph, which is of course the
situation we just discussed. The second subsection is an extended exercise that uses backtracking in the context of
On occasion, we need to navigate through a maze of one-way streets. Or, we may wish to draw a graph of whom we
consider a friend, whom they consider a friend, and so on. Or, we need to plan a route through a network of pipelines.
Or, we ask the Internet to find some way to send a message from one place to another.
All these situations share a common element: a
Specifically, there is always some collection of
and a collection of
. The edges represent one-way
connections between the nodes. Consider figure
. The black bullets are the nodes; the arrows between them are the
one-way connections. The sample graph consists of seven nodes and nine edges.
Now suppose we wish to plan routes in the graph of figure
. For example, if we plan to go from C to D, the route is
simple: it consists of the origination node C and the destination node D. In contrast, if we wish to travel from E to D,
we have two choices:
We either travel from E to F and then to D.
Or, we travel from E to C and then to D.
For some nodes, however, it is impossible to connect them. In particular, it is impossible in our sample graph to move
from C to G by following the arrows.
A directed graph
In the real world, graphs have more than just seven nodes and many more edges. Hence it is natural to develop
functions that plan routes in graphs. Following the general design recipe, we start with a data analysis. Here is a
../How%20to%20Design%20Programs/curriculum-Z-H-35.html (1 of 7) [2/5/2008 4:54:08 PM]