How to Design Programs: An Introduction to Programming and Computing

Info icon This preview shows pages 1–3. Sign up to view the full content.

How to Design Programs: An Introduction to Computing and Programming [Go to first , previous , next page; contents ; index ] Section 28 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 chess. 28.1 Traversing Graphs 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 directed graph . Specifically, there is always some collection of nodes and a collection of edges . The edges represent one-way connections between the nodes. Consider figure 76 . 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 76 . 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: 1. We either travel from E to F and then to D. 2. 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. [curriculum4a-Z-G-33.gif] Figure 76: 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 (1 of 7) [2/5/2008 4:54:08 PM]
Image of page 1

Info icon This preview has intentionally blurred sections. Sign up to view the full version.