Data Structures in C++:Sample Code

Sample Code

To illustrate some of the STL routines in one place, we provide an implementation of a routine that finds word ladders. A word ladder transforms one word to another by changing one character at a time, with each change always resulting in a real word. For instance, we transform those to where using the word ladder: those, these, there, where. See [2] for a description of this problem. The word ladder problem is a standard unweighted shortest path problem, and in the typical application of five-letter words, a quadratic algorithm is acceptable. Figures 42.7 to 42.9 show some of the routines (omitting error checks, function prototypes, and a main that reads the word list and prompt for word pairs), which for the most part are straightforward.

computeAdjacentWords, shown in Figure 42.7, uses the same idiom seen in Figure 42.2

(dealing with email aliases).

In Figure 42.8 we see two versions of find Chain.

The return value for find Chain is a map in which the key is a word, and the value is an adjacent word on the chain back towards

image

the first word (or "" if there is no chain, or if the key is first). The shorter version of find Chain takes a vector containing the words, computes the map of adjacent words, and then invokes the longer version of find Chain. Because the map in find Chain is passed by constant reference, operator[] is not available, and instead we access values in the map by using the iterator returned by a call to find.

image

image

Finally, in Figure 42.9 we see the routine that returns, as a vector<string>, the chain of words given the map computed by the shortest path algorithm in find Chain. The function get Chain From Previous Map passes the first parameter by reference instead of the more natural constant reference to allow the use of operator[] to access the map. Although this is simpler to code, it is arguably inferior from a software design standpoint because it changes the parameter passing mode simply to allow expedient code.

Acknowledgment

This work was supported, in part, by the National Science Foundation under grant EIA- 9906600. Parts of this chapter are based upon the author’s work in [9].

Comments

Popular posts from this blog

Data Structure Visualization:Introduction and Value of Data Structure Rendering

Collision Detection:Penetration Depth Computation

Concurrent Data Structures:Linked Lists