258 Chapter 11 Deques { Double Ended Data Structures Chapter - - PDF document

258 chapter 11 deques double ended data structures
SMART_READER_LITE
LIVE PREVIEW

258 Chapter 11 Deques { Double Ended Data Structures Chapter - - PDF document

258 Chapter 11 Deques { Double Ended Data Structures Chapter Ov erview In this c hapter w e will not only in tro duce the deque data structure from the standard template library , but also use the data t yp e


slide-1
SLIDE 1 258
slide-2
SLIDE 2 Chapter 11 Deques { Double Ended Data Structures Chapter Ov erview In this c hapter w e will not
  • nly
in tro duce the deque data structure from the standard template library , but also use the data t yp e to illustrate t w
  • imp
  • rtan
t general searc h tec hniques, depth and breadth rst searc h. Next, w e will
  • nce
again revisit the topic
  • f
inheritance, in tro duced in Chapter 9, sho wing ho w inheritance can b e used to construct fr ameworks, whic h are sk eleton applications used as the basis for solving similar problems. Finally , w e conclude the c hapter b y presen ting a simplied deque implemen tation, similar to the standard library data structure.
  • The
deque abstraction
  • Depth
and Breadth rst searc hing
  • F
ramew
  • rks
  • A
Simplied Implemen tation 11.1 The Deque abstraction The deque data t yp e (pronounced either \dec k"
  • r
\DQ") is
  • ne
  • f
the most in teresting data structures in the standard template library . Of all the STL con tainers, the deque is the least con v en tional. It represen ts a data t yp e that is seldom considered to b e
  • ne
  • f
the \classic" data abstractions, as are v ectors, lists, sets
  • r
trees. Nev ertheless, the deque is a p
  • w
erful and v ersatile abstraction. 259
slide-3
SLIDE 3 260 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES The
  • p
erations pro vided b y the deque data t yp e, sho wn in Figure 11.1, are a com bination
  • f
those pro vided b y the classes vecto r and list. Lik e a v ector, the deque is a randomly accessible structure. This means that instances
  • f
the class deque can b e used in most situations in whic h a v ector migh t b e emplo y ed. Lik e a list, elemen ts can b e inserted in to the middle
  • f
a deque, although suc h insertions are not as ecien t as they are with a list. The term deque is short for Double-Ende d QUEue, and describ es the structure w ell. The deque is a com bination
  • f
stac k and queue, allo wing elemen ts to b e inserted at either end. Whereas a vecto r
  • nly
allo ws ecien t insertion at
  • ne
end, the deque can p erform insertion in constan t time at either the fron t
  • r
the end
  • f
the con tainer. Lik e a v ector, a deque is a v ery space ecien t structure, using far less memory for a giv en size collection than will, for example, a list. Ho w ev er, again lik e a v ector, insertions in to the middle
  • f
the structure are p ermitted, but are not ecien t. An insertion in to a deque ma y require the mo v emen t
  • f
ev ery elemen t in the collection, and is th us O (n) w
  • rst
case.
  • One
  • f
the most common uses for a deque is as an underlying con tainer for either a stack
  • r
a queue. The deque is a preferable con tainer for suc h emplo ymen t if the size
  • f
the collection remains relativ ely stable during the course
  • f
execution, while if the size v aries widely a list
  • r
vecto r is preferable. In man y cases the decision concerning whic h structure is most appropriate can
  • nly
b e made b y p erforming direct measuremen t
  • f
program size
  • r
execution time. Because the meaning
  • f
the
  • p
erations
  • n
a deque are similar to those
  • f
a v ector
  • r
a list w e will not describ e them in detail. Instead, w e will pro ceed to an example program that mak es use
  • f
the features pro vided b y a deque. 11.2 Application{Depth and Breadth First Searc h In this section w e will examine a program that will disco v er a path through a maze, suc h as the
  • ne
sho wn b elo w. W e will assume that the starting p
  • in
t for the searc h is alw a ys in the lo w er righ t corner
  • f
the maze, and the goal is the upp er left corner. F S
slide-4
SLIDE 4 11.2. APPLICA TION{DEPTH AND BREADTH FIRST SEAR CH 261 Constructors and Assignmen t deque<T> d; default constructor deque<T> d (anInt); construct with initial size deque<T> d (anInt, a T value); construct with initial size and initial v alue deque<T> d (aDeque); cop y constructor d = aDeque; assignmen t
  • f
deque from another deque d.sw ap (aDeque); sw ap con ten ts with another deque Elemen t Access and Insertion d[i] subscript access, can b e assignmen t target d.front () rst v alue in collection d.back () nal v alue in collection d.insert (iterator, value) insert v alue b efore iterator d.push front (value) insert v alue at fron t
  • f
con tainer d.push back (value) insert v alue at bac k
  • f
con tainer Remo v al d.pop front () remo v e elemen t from fron t
  • f
v ector d.pop back () remo v e elemen t from bac k
  • f
v ector d.erase (iterator) remo v e single elemen t d.erase (iterator,iterat
  • r
) remo v e range
  • f
elemen ts Size d.size () n um b er
  • f
elemen ts curren tly held d.empty () true if v ector is empt y Iterators deque<T>::iterato r itr declare a new iterator d.b egin () starting iterator d.end () stopping iterator d.rb egin () starting iterator for rev erse access d.rend () stopping iterator for rev erse access T able 11.1: Summary
  • f
deque
  • p
erations
slide-5
SLIDE 5 262 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES Our purp
  • se
in presen ting this example is not
  • nly
to con trast t w
  • dieren
t t yp es
  • f
searc h tec hniques, but also to demonstrate the
  • p
erations
  • f
the deque data t yp e, and nally to sho w ho w a deque can b e used either in a stac k-lik e
  • r
queue-lik e fashion. These t w
  • broad
approac hes to searc hing are kno wn as depth rst se ar ch and br e adth rst se ar ch. W e w an t the maze searc hing program to b e general, able to solv e an y t w
  • dimensional
maze and not simply the example maze sho wn ab
  • v
e. W e therefore design a sc heme so that the description
  • f
the maze can b e read from an input le. Dieren t les can b e used to test the program
  • n
a v ariet y
  • f
dieren t mazes. T
  • see
ho w to do this, note that a maze can b e describ ed as a sequence
  • f
squares,
  • r
c el ls. The example maze sho wn ab
  • v
e, for example, is a v e b y v e square
  • f
25 cells. Eac h cell can b e c haracterized b y a n um b er, whic h describ es the surrounding w alls. Sixteen n um b ers are sucien t. In this fashion w e ha v e the follo wing v
  • cabulary
for describing cells: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 The pattern
  • f
the n umeric v alues b ecomes apparen t if
  • ne
considers the n um b er not as a decimal v alue, but as a binary pattern. The 1's p
  • sition
indicates the presence
  • r
absence
  • f
a south w all, the 2's p
  • sition
the east w all, the 4's p
  • sition
the north w all, and the 8's p
  • sition
the w est w all. A v alue suc h as 13 is written in binary as 1101. This indicates there are w alls to the north, w est, and south, but not the east. Using this sc heme, the example maze could b e describ ed b y 25 in teger v alues. In the fol- lo wing w e ha v e sup erimp
  • sed
these v alues
  • n
the maze, to b etter illustrate their relationship to the
  • riginal
structure. 9 1 1 3 11 14 14 10 12 2 9 5 2 13 2 10 9 4 3 10 14 12 5 4 6 This external represen tation
  • f
the maze m ust b e mapp ed
  • n
to an internal represen- tation. The in ternal represen tation need not matc h the external represen tation, as long as there is a means
  • f
con v ersion b et w een the t w
  • .
The in ternal represen tation will again b e a sequence
  • f
cells. Eac h cell is an instance
  • f
the class cell. Instances
  • f
class cell main tain three data elds:
slide-6
SLIDE 6 11.2. APPLICA TION{DEPTH AND BREADTH FIRST SEAR CH 263
  • A
n um b er. This is an in teger v alue used to iden tify the cell. Cells are n um b ered consecutiv ely from left to righ t and top to b
  • ttom.
  • A
list
  • f
neigh b
  • ring
cells. Eac h cell will ha v e an en try in this list for all
  • ther
neigh b
  • r
cells that can b e reac hed.
  • A
Bo
  • lean
v alue, named visited, that will b e used to mark a cell
  • nce
it has b een visited. T ra v ersing a maze
  • ften
results in dead-ends, and the need to bac k up and start again. Marking visited cells a v
  • ids
rep eating eort and p
  • ten
tially w alking around in circles. A class description for cell is sho wn b elo w. The mem b er function addNeighb
  • r
simply inserts a v alue in to the list
  • f
neigh b
  • rs.
The mem b er function visit will enco de the searc hing algorithm. W e will defer a description
  • f
this un til after w e ha v e
  • utlined
the rest
  • f
the program. class cell f public: // constructor cell (int n) : number(n), visited(false) f g //
  • p
erations void addNeighbor (cell
  • n)
f neighbors.push back(n); g void visit (deque<cell > &); protected: int number; bool visited; list <cell > neighbors; g; The class that represen ts the en tire maze structure is called maze, and has the follo wing structure: class maze f public: maze (istream &); void solveMaze (); protected: cell
  • start;
bool finished; deque <cell > path; g;
slide-7
SLIDE 7 264 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES The class maze main tains three data elds. The rst is a p
  • in
ter to the starting cell. The second is a Bo
  • lean
ag that is set to true
  • nce
the goal cell has b een reac hed. The third data eld is a deque, used to hold the path (or paths) curren tly b eing tra v ersed. The constructor for the class maze, sho wn in Figure 11.1, reads the maze description from an input le (passed as argumen t), con v erting from the external represen tation to the in ternal represen tation. The rst t w
  • in
teger v alues in the le represen t the n um b er
  • f
ro ws and columns
  • f
the maze. In
  • rder
to set the links prop erly , a vecto r is main tained that represen ts the cells in the ro w pr evious to the ro w curren tly b eing read from the input le. (This is the ro w to the immediate north
  • f
the curren t). Recall that the t w
  • argumen
t form used in the constructor for this v ector initializes eac h en try to the second argumen t v alue, in this case a n ull p
  • in
ter v alue. After eac h new cell has b een pro cessed, the en try in this v ector for the corresp
  • nding
column has c hanged. The follo wing picture illustrates the use
  • f
this v ector. Here the rst t w
  • ro
ws ha v e b een pro cessed, and the rst t w
  • columns
in the third ro w. The b
  • xed
elemen ts indicate the curren t v alue
  • f
the v ector. Note that the v alue
  • f
the v ector with the same column n um b er as the presen t elemen t is the neigh b
  • r
to the north, while the v alue with the index
  • ne
smaller than the curren t column is the neigh b
  • r
to the east. 9 5 2 10 9 4 3 10 14 12 5 4 6 As eac h new v alue is read, it is determined whether
  • r
not it has a link to the north (to the previous ro w)
  • r
to the w est (to the most recen tly pro cessed cell). If so, then links are established. Notice that links cannot b e created to the east and south, since these cells ha v e not y et b een created. Ho w ev er, note that a link to the south
  • r
east corresp
  • nds
to a link from the north
  • r
w est in the adjoining cells, so b y making b
  • th
sets
  • f
connections at
  • nce
it is
  • nly
necessary to recognize north and w est connections. After the cell has b een completely pro cessed, it is assigned to the corresp
  • nding
p
  • sition
in the v ector, and the next elemen t is read. 9 5 2 13 10 9 4 3 10 14 12 5 4 6 This pro cess con tin ues un til all the maze description v alues ha v e b een read. Ha ving en tered the maze data, w e can no w describ e the algorithm used to solv e the maze. The fundamen tal problem
  • ccurs
when there is a c hoice
  • f
sev eral directions to pursue. In
  • ur
example maze, this
  • ccurs
immediately after the rst step, when there are p
  • ssible
mo v es
slide-8
SLIDE 8 11.2. APPLICA TION{DEPTH AND BREADTH FIRST SEAR CH 265 maze::maze (istream & infile) // initialize maze b y reading from le f int numRows, numColumns; int counter = 1; cell
  • current
= 0; // read n um b er
  • f
ro ws and columns infile >> numRows >> numColumns; // create v ector for previous ro w vector <cell > previousRow (numRows, 0); // no w read data v alues for (int i = 0; i < numRows; i++) for (int j = 0; j < numColumns; j++) f current = new cell(counter++); int walls; infile >> walls; // mak e north connections if ((i > 0) && ((walls & 0x04) == 0)) f current->addNeigh bor (previousRow[j] ); previousRow[j]->a ddN ei gh bor (current); g // mak e w est connections if ((j > 0) && ((walls & 0x08) == 0)) f current->addNeigh bor (previousRow[j- 1]) ; previousRow[j-1]- >ad dN ei ghb
  • r
(current); g previousRow[j] = current; g // most recen tly created cell is start
  • f
maze start = current; finished = false; g Figure 11.1: Constructor for class maze.
slide-9
SLIDE 9 266 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES b
  • th
north and w est. One
  • r
the
  • ther
paths m ust b e selected. Ho w ev er, since a selection ma y ultimately b e wrong (resulting in a dead end), it is imp
  • rtan
t to k eep trac k
  • f
the alternativ e p
  • ssibilities.
W e do so using a deque. A t eac h step the deque will hold p
  • in
ters to cells that are kno wn to b e reac hable, but ha v e not y et b een visited. Describing the rst few steps in the pro cess will clarify the approac h. There is
  • nly
  • ne
cell reac hable from the starting p
  • sition,
and th us initially the deque con tains
  • nly
  • ne
elemen t. The follo wing also rep eats the maze, with the cells sho wing their giv en n um b er. the deque front 20 back 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 This v alue is pulled from the deque, and the neigh b
  • rs
  • f
the cell inserted bac k in to the deque. This time there are t w
  • neigh
b
  • rs,
so the deque will ha v e t w
  • en
tries: front 19 15 back Only
  • ne
v alue can b e explored at an y time. So the rst elemen t is remo v ed from the deque, and its neigh b
  • rs
inserted, and so
  • n
rep eatedly . Tw
  • steps
later w e again ha v e a c hoice, and b
  • th
neigh b
  • rs
are inserted in to the deque. A t this p
  • in
t, the deque as the follo wing con ten ts: front 22 18 15 back The next cell to b e explored will b e 22, but cells 18 and 15 are also kno wn to b e reac hable, and are w aiting to b e considered should the curren t path not pro v e to b e a solution. This in fact
  • ccurs
when w e reac h cell 16, at whic h p
  • in
t the deque lo
  • ks
as follo ws: front 16 17 18 15 back Since cell 16 adds no new v alues to the deque (ha ving no un visited neigh b
  • rs)
the next en try is automatically p
  • pp
ed from the deque. In this fashion w e start pursuing the path from 17, whic h also immediately dead-ends. Finally , the en try 18 is p
  • pp
ed from the deque, and the searc h con tin ues. The solution is ultimately found in fteen steps. The follo wing sho ws the path to the solution, with the cells n um b ered in the
  • rder
in whic h they w ere considered.
slide-10
SLIDE 10 11.2. APPLICA TION{DEPTH AND BREADTH FIRST SEAR CH 267 1 2 3 4 5 6 7 8 9 10 11 12 13 14 The co de to p erform this searc h is found in t w
  • metho
ds. The
  • v
erall con trol is the function solveMaze in class maze. This function pulls cells from the deque as long as the deque remains nonempt y and the solution has not y et b een found. void maze::solveMaze () // solv e the maze puzzle f start->visit (path); while ((! finished) && (! path.empty ())) f cell
  • current
= path.front (); path.pop front (); finished = current->visit (path); g if (! finished) cout << "no solution found\n"; g When eac h cell is visited, it places all un visited neigh b
  • rs
in to the deque. bool cell::visit (deque<cell > & path) // visit cell, place neigh b
  • rs
in to queue // return true if solution is found f if (visited) // already b een here return false; visited = true; // mark as visited cout << "visiting cell " << number << endl; if (number == 1) f cout << "puzzle solved\n"; return true; g // put neigh b
  • rs
in to deque list <cell >::iterator start, stop;
slide-11
SLIDE 11 268 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES start = neighbors.begin (); stop = neighbors.end (); for ( ; start != stop; ++start) if (! (start)->visited ) path.push front (start); return false; g The strategy em b
  • died
in this co de doggedly pursues a single path un til it either reac hes a dead-end
  • r
un til the solution is found. When a dead-end is encoun tered, the most recen t alternativ e path is reactiv ated, and the searc h con tin ues. This approac h is called depth-rst se ar ch, since it mo v es deeply in to the structure b efore examining alternativ es. Depth rst searc h is the t yp e
  • f
searc h a single individual migh t p erform in w alking through a maze. Supp
  • se,
  • n
the
  • ther
hand, that there is a group
  • f
p eople w alking through the maze. When a c hoice
  • f
alternativ e directions is encoun tered, the group ma y decide to split itself in to t w
  • smaller
groups, and pursue eac h path sim ultaneously . When another c hoice is reac hed the group again splits, and so
  • n.
In this manner all p
  • ten
tial paths are in v estigated at the same time. Suc h a strategy is kno wn as br e adth rst se ar ch. What is in triguing ab
  • ut
the maze searc hing algorithm is that the co de for breadth rst searc h is almost iden tical to the co de for depth rst searc h. In fact, all that is necessary is to c hange the command path.push front in the visited mem b er function to instead p erform a path.push back. bool cell::visit (deque<cell > & path) f ... for ( ; start != stop; ++start) if (! (start)->visited ) path.push back (start); // <- note c hange return false; g In doing so, w e c hange
  • ur
use
  • f
the deque from b eing stac k-lik e, to b eing queue-lik e. This can b e illustrated b y
  • nce
more describing the state
  • f
the deque at v arious p
  • in
ts during execution. F
  • r
example, after the rst step, the deque has the follo wing v alues. Note ho w the elemen ts are in the
  • pp
  • site
  • rder
from the
  • ne
they held in the depth rst searc hing algorithm. front 15 19 back
slide-12
SLIDE 12 11.2. APPLICA TION{DEPTH AND BREADTH FIRST SEAR CH 269 The elemen t 15 is pulled from the deque, but its neigh b
  • rs,
the cells 10 and 14, are placed
  • n
the b ack
  • f
the queue. The next no de to b e in v estigated will therefore not b e
  • ne
  • f
the immediate neigh b
  • rs
  • f
the most recen t no de, but an en tirely dieren t path altogether. front 15 10 14 back A few steps later the searc h has b een split sev eral times, and the deque con tains the follo wing v alues: front 17 21 2 8 8 12 back As
  • ne
migh t exp ect, a breadth rst searc h is more thorough, but ma y require more time than a depth rst searc h. Recall that the depth rst searc h w as able to disco v er the solution in 15 steps. The depth rst searc h is still lo
  • king
after 20 steps. The follo wing describ es the searc h at this p
  • in
t. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 T race carefully the sequence
  • f
the last few cells that w ere visited. Note ho w the searc h has jump ed around all
  • v
er the maze, exploring a n um b er
  • f
dieren t alternativ es at the same time. Another w a y to imagine breadth rst searc h is that it describ es what w
  • uld
happ en if
  • ne
w ere to p
  • ur
ink in to the maze at the starting lo cation, as the ink slo wly p ermeates ev ery path un til the solution is reac hed. Depth rst and breadth rst are b
  • th
v aluable tec hniques in a v ariet y
  • f
searc hing problems, and arise in a n um b er
  • f
dieren t forms and con texts. The follo wing dierences can b e noted in comparing breadth-rst and depth-rst searc hing.
  • Since
all paths
  • f
length
  • ne
are in v estigated b efore examining paths
  • f
length t w
  • ,
and all paths
  • f
length t w
  • b
efore examining paths
  • f
length three, a breadth-rst searc h is guaran teed to alw a ys disco v er a path from start to goal con taining few est steps, whenev er suc h a path exists.
  • Since
  • ne
path is in v estigated b efore an y alternativ es are examined, a depth rst searc h may, if it is luc ky , disco v er a solution more quic kly than the equiv alen t breadth-rst algorithm. Notice this
  • ccurs
here, where the goal is encoun tered after examining
  • nly
15 lo cations in the depth-rst algorithm, while the goal is
  • nly
reac hed after
slide-13
SLIDE 13 270 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES 1 2 3 4
  • A
A A U H H H j H H H Y A A A K
  • *
5 6 7 8 Figure 11.2: Legal knigh t mo v es 25 iterations in the breadth-rst algorithm. But this b enet is not certain, and a bad selection
  • f
alternativ es to pursue can lead to man y dead-end searc hes b efore the prop er path to the goal is rev ealed.
  • In
particular, supp
  • se
for a particular problem that some but not all paths are innite, and there exists at least
  • ne
path from start to goal that is nite. Breadth-rst searc h is guaran teed to nd a shortest solution. Depth rst searc h ma y ha v e the unfortunate luc k to pursue a nev er-ending path, and can hence fail to nd a solution. 11.3 Application{A F ramew
  • rk
for Bac ktrac king If w e generalize the approac h used in the depth rst searc h solution
  • f
the maze, w e disco v er a tec hnique termed b acktr acking. T
  • use
bac ktrac king, a problem m ust ha v e the c haracteristic that a solution is disco v ered as a sequence
  • f
steps. A t some
  • f
these steps there ma y b e m ultiple alternativ e c hoices for the next step, and insucien t information to decide whic h alternativ e will ultimately b e the correct c hoice. A stac k is used to record the state
  • f
the computation at the p
  • in
t
  • f
c hoice, p ermitting the program to subsequen tly \restart" the calculation from that p
  • in
t and pursue a dieren t alternativ e. T
  • illustrate
the idea
  • f
bac ktrac king, w e will analyze a classic puzzle in v
  • lving
the knigh t c hess-piece. In c hess, a knigh t can legally mo v e in an \L" shap ed pattern, either
  • ne
forw ard
  • r
bac kw ard and t w
  • left
  • r
righ t,
  • r
t w
  • forw
ard
  • r
bac kw ard and
  • ne
left
  • r
righ t. Figure 11.2 illustrates the legal mo v es for a knigh t starting in the giv en p
  • sition
  • n
a con v en tional 8-square c hess b
  • ard.
A piece ma y not mo v e
  • the
b
  • ard,
so near the edges
  • f
the b
  • ard
the n um b er
  • f
legal mo v es ma y b e less than eigh t. A knights-tour is a sequence
  • f
64 mo v es in whic h a knigh t visits, using
  • nly
legal mo v es, eac h and ev ery square
  • n
the b
  • ard
  • nce.
The classic knigh ts-tour problem is to disco v er
slide-14
SLIDE 14 11.3. APPLICA TION{A FRAMEW ORK F OR BA CKTRA CKING 271 a knigh ts tour starting from a sp ecic lo cation. F
  • r
example, the follo wing table sho ws the steps in a complete knigh ts-tour starting from the upp er left corner. 1 10 31 64 33 26 53 62 12 7 28 25 30 63 34 51 9 2 11 32 27 52 61 54 6 13 8 29 24 35 50 41 3 18 5 36 49 40 55 60 14 21 16 23 46 57 42 39 17 4 19 48 37 44 59 56 20 15 22 45 58 47 38 43 As an illustration
  • f
bac ktrac king, consider the follo wing state in whic h
  • ur
program nds itself rather early in the searc h for a solution after ha ving successfully p erformed 57 mo v es. There is no legal un visited lo cation to whic h the piece at mo v e 57 can adv ance. The program will \bac k-up" to mo v e 56, and try a dieren t alternativ e. But in fact there is no
  • ther
alternativ e p
  • ssible
at mo v e 56, and so the program will bac k up to mo v e 55, and then to 54, 53, and 52. It is
  • nly
at mo v e 52 that a new un tried legal alternativ e is disco v ered, namely to mo v e to the b
  • ttom
left corner. This mo v e is tried, but then immediately abandoned since there is no successor. No further alternativ e is p
  • ssible
for mo v e 52, nor for mo v e 51,
  • r
50. W e m ust bac ktrac k all the w a y to mo v e 49 b efore w e can nd another p
  • ssibilit
y , whic h is to mak e the new mo v e 50 b e the no w v acan t lo cation
  • f
the previous mo v e 52. 1 10 31 33 26 57 42 12 7 28 25 30 43 50 9 2 11 32 27 34 41 56 6 13 8 29 24 49 44 51 3 18 5 38 35 40 55 14 21 16 23 48 37 52 45 17 4 19 36 39 46 54 20 15 22 47 53 Non-recursiv e programs that solv e a problem using bac ktrac king generally ha v e a v ery similar structure. W e can use this
  • bserv
ation to dev elop a generic fr amework for suc h problems. A framew
  • rk
is a class (or, in more complicated situations, a set
  • f
classes and functions), that together pro vide the sk eleton
  • utline
for the solution to some problem, but do not pro vide an y sp ecic details. The most common framew
  • rks
are asso ciated with graphical user in terfaces, but man y
  • ther
t yp es
  • f
framew
  • rks
are p
  • ssible.
T
  • generate
a
slide-15
SLIDE 15 272 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES solution to a sp ecic problem the programmer sp ecializes the framew
  • rk,
generally using inheritance. 11.3.1 Sp ecialization using Inheritance As w e noted in Chapter 9, inheritanc e is a p
  • w
erful mec hanism for quic kly and easily creating new data abstractions that are v ariations
  • r
extensions
  • f
existing soft w are. T
  • use
inheritance, the programmer writes the name
  • f
the existing class (called the p ar ent class) follo wing the name
  • f
the new class. By doing so, the new class (called the child class,
  • r
sometimes the derive d class) is then treated as an extension
  • f
the
  • lder
class. All data elds, all mem b er functions
  • f
the existing structure are therefore immediately accessible in the new structure. In addition, the programmer can add new data elds and new functions. W e will illustrate the use
  • f
inheritance in the dev elopmen t
  • f
  • ur
framew
  • rk
for bac k- trac king problems. The solution to a generic bac ktrac king problem can b e describ ed as follo ws: template <class T> bool backtrackFramewo rk< T> ::r un () f // initialize the problem initialize (); done = false; // do the main lo
  • p
while ((! done) && (! theStack.empty ())) f // if w e can't adv ance from curren t state // then p
  • p
the stac k if (! advance(theStack. to p ())) theStack.pop (); g // return true if stac k is not empt y return ! theStack.empty (); g A pro cedure initialize is used to establish whatev er conditions need b e set to start the problem; including pushing the rst state
  • n
the stac k. A Bo
  • lean
v ariable done indicates when the problem is nished. This v ariable ma y b e set b y the application sp ecic co de to terminate the lo
  • p
early if, for example, a solution is found. The heart
  • f
the algorithm is a simple lo
  • p.
A t eac h step a pro cedure called advance is called, passing as argumen t the curren t state. If it is p
  • ssible
to adv ance to a new state then execution con tin ues,
  • therwise
the topmost state is p
  • pp
ed
  • the
stac k, and execution bac ktrac ks to a previous p
  • in
t.
slide-16
SLIDE 16 11.3. APPLICA TION{A FRAMEW ORK F OR BA CKTRA CKING 273 The metho d just giv en is from a class called backtrackFramewo rk . The template pa- rameter is the class used to enco de state information. The complete class description is as follo ws: // // class bac ktrac kF ramew
  • rk
// general framew
  • rk
for solving problems // in v
  • lving
bac ktrac king // template <class T> class backtrackFramew
  • rk
f public: // proto col for bac ktrac k problems virtual void initialize (); virtual bool advance (T newstate); virtual bool run (); protected: stack < deque <T> > theStack; bool done; g; Note that the general purp
  • se
class has no information sp ecic to the knigh ts tour problem. In
  • rder
to sp ecialize this general approac h to mak e a solution to the knigh ts- tour problem, w e rst need to describ e ho w w e record information concerning the curren t p
  • sition.
The encapsulation for the \state"
  • f
the searc h at an y p
  • in
t will b e an instance
  • f
a class w e will call Position. A Position corresp
  • nds
to a lo cation
  • n
the c hess b
  • ard.
A p
  • sition
will main tain a pair
  • f
x and y v alues corresp
  • nding
to co
  • rdinates
  • n
the b
  • ard,
a v ariable moveNumber that will record the sequence
  • f
mo v es in the solution, and a fourth in teger v ariable, named visited, that will indicate what subsequen t mo v es ha v e b een attempted. T
  • enco
de this last v alue, w e will simply try , at eac h step, the mo v es in
  • rder
and n um b ered as in Figure 11.2. A zero stored in the visited v ariable indicates the p
  • sition
has not y et b een used
  • n
the knigh ts tour, while a non-zero v alue indicates the p
  • sition
has b een used
  • n
the knigh ts tour, and furthermore the t yp e
  • f
mo v e that w as used to generate the next step. The follo wing is the class description for Position. The
  • utput
  • p
erator is used to prin t the nal result. // // class P
  • sition
// record a p
  • sition
in the knigh ts mo v e tour
slide-17
SLIDE 17 274 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES // class Position f // p
  • sition
in c hessb
  • ard
public: void init (int, int); Position
  • nextPosition
(); protected: // data elds // x and y are co
  • rdinate
p
  • sitions
int x, y; // mo v eNum b er records the sequence
  • f
steps int moveNumber; // visited is a bit v ector marking what p
  • sitions
ha v e b een visited int visited; // in ternal metho d used to nd the next mo v e Position
  • findMove(int
visitedPosition); // friends friend class knightsTour; friend
  • stream
&
  • perator
<< (ostream &
  • ut,
Position & v); g; The c hessb
  • ard
itself will simply b e declared as a t w
  • -dimensional
matrix
  • f
p
  • sitions,
named board. Because the arra y constructor do es not p ermit the initialization
  • f
eac h p
  • sition
individually , initialization
  • f
eac h elemen t is p erformed with a lo
  • p
that simply in v
  • k
es the init metho d for eac h v alue. W e will see this shortly in the initialization p
  • rtion
  • f
the program. A hallmark
  • f
  • b
ject-orien ted programming and the resp
  • nsibilit
y driv en design tec h- nique w e
  • utlined
in Chapter 2 is the concept
  • f
making data structures resp
  • nsible
for their
  • wn
  • p
eration. The Position data structure illustrates this idea. Eac h p
  • sition
is resp
  • nsible
for nding the next p
  • ten
tial mo v e in the solution. The pro cess
  • f
nding the solution is p erformed b y the metho d nextPosition. This metho d returns a p
  • in
ter to a p
  • sition,
returning a n ull p
  • in
ter if no legal alternativ e exists. In
  • rder
to disco v er a p
  • sition,
the metho d incremen ts the v alue held in the v ariable visited, using the facilitator metho d findMove to p erform the enco ding
  • f
the n um b er in to a p
  • sition
v alue. If the in- cremen ted v alue
  • f
the visited v ariable denotes a p
  • sition
that is legal and not y et visited, it is returned. Otherwise the lo
  • p
con tin ues. If all 8 p
  • ssible
mo v es ha v e b een examined, then no alternativ e exists and a n ull v alue is returned. Before returning in this case w e zero the v ariable visited, so that the p
  • sition
can b e revisited along a dieren t path. W e sa w
slide-18
SLIDE 18 11.3. APPLICA TION{A FRAMEW ORK F OR BA CKTRA CKING 275 this in the earlier example
  • f
bac ktrac king, where p
  • sition
52 w as rst abandoned but later reac hed from a dieren t direction. Position
  • Position::nextPos
iti
  • n
() f while (++visited < 9) f Position
  • next
= findMove(visited) ; // if there is a neigh b
  • r
not visited then return it if ((next != 0) && (next->visited == 0)) return next; g // can't mo v e to an y neigh b
  • r,
rep
  • rt
failure visited = 0; return 0; g The metho d findMove simply translates a v alue b et w een 1 and 8 in to a p
  • sition,
ltering
  • ut
mo v es that are not
  • n
the b
  • ard.
Position
  • Position::findMov
e(i nt typ) f int nx, ny; switch(typ) f case 1: nx = x
  • 1;
ny = y
  • 2;
break; case 2: nx = x + 1; ny = y
  • 2;
break; case 3: nx = x
  • 2;
ny = y
  • 1;
break; case 4: nx = x + 2; ny = y
  • 1;
break; case 5: nx = x
  • 2;
ny = y + 1; break; case 6: nx = x + 2; ny = y + 1; break; case 7: nx = x
  • 1;
ny = y + 2; break; case 8: nx = x + 1; ny = y + 2; break; g // return n ull v alue
  • n
illegal p
  • sitions
if ((nx < 0) jj (ny < 0)) return 0; if ((nx >= boardSize) jj (ny >= boardSize)) return 0; // return address
  • f
new p
  • sition
return & board[nx][ny]; g
slide-19
SLIDE 19 276 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES W e are nally in a p
  • sition
to sho w ho w to use inheritance to sp ecialize the general purp
  • se
bac ktrac king solution w e created earlier in
  • rder
to create a solution to the knigh ts tour problem. T
  • create
a solution to the knigh ts tour problem w e need to tie the Position data structure in to
  • ur
bac ktrac king framew
  • rk.
By sa ying that the new class knightsT
  • ur,
inherits from backtrackF ramew
  • rk
(a pro cess termed derivation), all the data elds and metho ds
  • f
the paren t class are made a v ailable to the new class. In addition, those metho ds that w ere lab eled virtual in the paren t class can b e
  • verridden,
and pro vided with new meanings. It is in this fashion that the initialize and the advance metho ds can b e made sp ecic to the curren t problem. The complete class description is as follo ws: // // class knigh tsT
  • ur
// solv e the n b y n knigh ts tour problem // class knightsTour : public backtrackFramewo rk <Po si ti
  • n
> f public: // redene the bac ktrac king proto col virtual void initialize (); virtual bool advance (Position ); // new metho d void solve (); g; The initialization metho d lo
  • ps
  • v
er eac h b
  • ard
p
  • sition
to establish the initial condi- tions for eac h v alue. It then pushes the starting lo cation, b
  • ard
p
  • sition
0:0,
  • n
to the stac k. This b
  • ard
p
  • sition
is
  • ur
initial state. const int boardSize = 8; Position board[boardSize][ bo ard Si ze] ; void knightsTour::ini ti ali ze () f // initialize the paren t class backtrackFramewor k< Pos it ion >::initialize (); // initialize c hessb
  • ard
for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) board[i][j].init (i, j);
slide-20
SLIDE 20 11.3. APPLICA TION{A FRAMEW ORK F OR BA CKTRA CKING 277 Ov erriding, Replacemen t and Renemen t Placing the mo dier virtual in the paren t class indicates that the giv en metho d can p
  • ten
tially b e replaced b y a function dened in a c hild class. This is
  • nly
a p
  • ten
tial, it need not b e replaced, and if not the function in the paren t will b e used. If a c hild class do es
  • v
erride the paren t class metho d, it is a complete replacemen t
  • f
the metho d from paren t class. Sometimes, as in the initialization metho d sho wn, w e instead w an t to c
  • mbine
the new co de with that
  • f
the paren t, making sure that b
  • th
are executed. In C ++ this is accomplished b y in v
  • king
the function in the paren t class from inside the co de for the c hild class. In
  • rder
to a v
  • id
confusion, the fully qualied name, in this case backtrackFramewor k< Pos it ion >::initialize (); is used to completely and fully sp ecify exactly what function should b e executed. // set mo v e n um b er
  • n
rst p
  • sition
board[0][0].moveN um ber = 1; // push initial p
  • sition
theStack.push(& board[0][0]); g T
  • complete
the framew
  • rk
w e need
  • nly
describ e ho w to disco v er the next mo v e from an y giv en p
  • sition.
This is p erformed b y the metho d advance. The advance metho d is giv en, in the argumen t, the curren t state. It asks a p
  • sition
to try to nd a next p
  • sition
in sequence. It do es this b y in v
  • king
the nextMove metho d w e describ ed earlier. The advance function returns a true v alue if adv ancemen t is p
  • ssible
from the curren t p
  • sition,
and a false v alue if no adv ancemen t can b e made. An additional resp
  • nsibilit
y is to test to see if the solution to the problem has b een found. If so, then the done ag m ust b e set. bool knightsTour::adv an ce( Po sit io n
  • currentPosition
) // try to adv ance from a giv en p
  • sition
f Position
  • newPosition
= currentPosition- >n ext Po sit io n (); if (newPosition) f // mo v e forw ard newPosition->mo veN um ber = currentPosition- >m
  • ve
Nu mbe r + 1; theStack.push(n ewP
  • s
iti
  • n
);
slide-21
SLIDE 21 278 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES // if w e ha v e lled all squares w e are done if (newPosition->mov eNu mb er == boardSize
  • boardSize)
done = true; // return success return true; g else return false; // can't mo v e forw ard g The nal metho d to describ e is the
  • ne
new metho d added b y class knightsTour to the framew
  • rk
proto col. This metho d simply starts the framew
  • rk
running. If success is rep
  • rted
then the stac k is p
  • pp
ed in
  • rder
to prin t the result. void knightsTour::sol ve () f // start framew
  • rk
if (run ()) f // prin t solution cout << "solution is:\n"; while (! theStack.empty ()) f cout <<
  • theStack.top
() << \n; theStack.pop (); g g else cout << "no solution "; g 11.4 An Implemen tation Of all the con tainers in the standard template library , the deque is the
  • ne
with the least
  • b
vious implemen tation approac h. T ec hniques for implemen ting v ectors, lists, queues, trees and so
  • n
are all w ell kno wn. But there are man y p
  • ssible
tec hniques that can b e used to implemen t a deque, and the language denition do es not constrain the soft w are dev elop er
  • f
the abstraction in an y signican t regard. In this section w e will describ e
  • ne
p
  • ssible
tec hnique. The approac h presen ted here has the adv an tage
  • f
b eing relativ ely simple, but is not the
  • nly
p
  • ssibilit
y . The basic idea in this implemen tation is to in ternally represen t a deque as a pair
  • f
v ectors. That is, while w e visualize a deque as a linear structure, suc h as the follo wing:
slide-22
SLIDE 22 11.4. AN IMPLEMENT A TION 279
  • 1
2 3 4
  • it
actually can b e stored in ternally as t w
  • v
ectors. This allo ws v alues to b e added at either end. Note, ho w ev er, that the rst v ector is \bac kw ards", as the rst elemen t is at the top, while the last elemen t is at the b
  • ttom,
in p
  • sition
0. 2 1 2 1 6 ? 3 4 6 ? 1 v ector index Figure 11.3 giv es a class description for
  • ur
simplied deque implemen tation, with man y
  • f
the shorter metho ds b eing dened as in-line pro cedures. The structure
  • f
most
  • f
the remaining
  • p
erations is v ery similar. All are implemen ted b y p erforming
  • p
erations
  • n
  • ne
  • r
the
  • ther
  • f
the underlying v ectors. The complicating factor is that either v ector could p
  • ten
tially b e empt y , in whic h case the
  • p
eration m ust b e p erformed
  • n
the
  • ther.
The metho d front, whic h returns the rst elemen t in the collection, is t ypical: template <class T> T & deque<T>::front () // return rst elemen t in deque f if (vecOne.empty ()) return vecTwo.front (); else return vecOne.back (); g If v ector
  • ne
is empt y , then the rst v alue in the deque is the rst v alue in v ector t w
  • .
If,
  • n
the
  • ther
hand, v ector
  • ne
is not empt y , then the rst v alue in the deque is the last v alue in the rst v ector. The metho d back is similar. The metho ds to remo v e an elemen t from either the fron t
  • r
the bac k
  • f
the collection are
  • nly
sligh tly more complex: template <class T> void deque<T>::pop front () // remo v e rst elemen t in deque
slide-23
SLIDE 23 280 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES // // class deque // double ended queue template <class T> class deque f public: typedef dequeIterator<T> iterator; typedef T value type; // constructors deque () : vecOne(), vecTwo() f g deque (unsigned int size, T & initial) : vecOne (size/2, initial), vecTwo (size
  • (size
/ 2), initial) f g deque (deque<T> & d) : vecOne(d.vecOne) , vecTwo(d.vecTwo) f g //
  • p
erations T &
  • perator
[ ] (unsigned int); T & front (); T & back (); bool empty () f return vecOne.empty () && vecTwo.empty (); g iterator begin () f return iterator(this, 0); g iterator end () f return iterator(this, size ()); g void erase (iterator); void erase (iterator, iterator); void insert (iterator, T &); int size () f return vecOne.size () + vecTwo.size (); g void push front (T & value) f vecOne.push back(value); g void push back (T & value) f vecTwo.push back(value); g void pop front (); void pop back (); protected: vector<T> vecOne; vector<T> vecTwo; g; Figure 11.3: A simplied implemen tation
  • f
the class deque.
slide-24
SLIDE 24 11.4. AN IMPLEMENT A TION 281 f if (vecOne.empty ()) vecTwo.erase(ve cTw
  • .
beg in ()); else vecOne.pop back (); g If the rst v ector is empt y , w e m ust erase the rst elemen t in the second v ector,
  • therwise
w e can simply reduce the size
  • f
the rst v ector b y
  • ne.
Note that this approac h ma y not b e the b est solution, as the erase
  • p
eration
  • n
v ector t w
  • is
almost undoubtedly v ery costly . Often sequences
  • f
pushes and p
  • ps
  • ccur
  • ne
after another. This w
  • uld
  • ccur,
for example, if the deque w ere used as a stac k
  • r
as a queue. Rather than eac h p
  • p
front causing an erase, a b etter alternativ e in this case w
  • uld
b e to mo v e some n um b er
  • f
elemen ts (for example half ) from the second v ector bac k to the rst. Subsequen t p
  • p
front
  • p
erations w
  • uld
then encoun ter the more ecien t p
  • p
back alternativ e, rather than the erase. The dev elopmen t
  • f
this p
  • ssibilit
y will b e explored in some
  • f
the exercises at the end
  • f
the c hapter. The subscript
  • p
erator c hanges the index v alues in to a subscript that is appropriate for
  • ne
  • f
the underlying v ectors. Notice that the subscripts m ust b e rev ersed for the rst v ector: template <class T> T & deque<T>::operato r [ ] (unsigned int index) // return giv en elemen t from deque f int n = vecOne.size (); if (index <= n) return vecOne [ (n-1)
  • index
]; else return vecTwo [ index
  • n
]; g 11.4.1 Deque Iterators An iterator for
  • ur
deque abstraction is most easily constructed b y using the subscript
  • p
erator to access the underlying elemen t. Suc h an approac h is sho wn in the class description in Figure 11.4. As with man y
  • f
the iterator implemen tations w e presen t, a ma jor dicult y arises from the need to supp
  • rt
b
  • th
a prex and a p
  • stx
form
  • f
the iterator
  • p
eration. The prex form is implemen ted in-line, as it simply c hanges the state
  • f
the curren t iterator and returns. The p
  • stx
form m ust c hange the curren t state, but return an iterator that describ es the lo cation prior to the c hange. This is most easily accomplished b y cloning the curren t iterator, whic h will preserv e the initial state, then up dating the v alue, and nally returning the clone.
slide-25
SLIDE 25 282 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES // // class dequeIterator // iterator proto col for deque template <class T> class dequeIterator f friend class deque<T>; typedef dequeIterator<T> iterator; public: // constructors dequeIterator (deque<T>
  • d,
int i) : theDeque(d), index(i) f g dequeIterator (deque<T>::iter ato r & d) : theDeque(d.theDe qu e), index(d.index) f g // iterator
  • p
erations T &
  • perator
  • ()
f return (theDeque)[inde x] ; g iterator &
  • perator
++ (int) f ++index; return this; g iterator
  • perator
++ (); // prex c hange iterator &
  • perator
  • (int)
f
  • -index;
return this; g iterator
  • perator
  • ();
// p
  • stx
c hange bool
  • perator
== (iterator & r) f return theDeque == r.theDeque && index == r.index; g bool
  • perator
< (iterator & r) f return theDeque == r.theDeque && index < r.index; g T &
  • perator
[ ] (unsigned int i) f return (theDeque) [index + i]; g void
  • perator
= (iterator & r) f theDeque = r.theDeque; index = r.index; g iterator
  • perator
+ (int i) f return iterator(theDequ e, index + i); g iterator
  • perator
  • (int
i) f return iterator(theDequ e, index
  • i);
g protected: deque<T>
  • theDeque;
int index; g; Figure 11.4: Implemen tation
  • f
a deque iterator.
slide-26
SLIDE 26 11.5. CHAPTER SUMMAR Y 283 template <class T> deque<T>::iterato r dequeIterator<T>: :o per at
  • r
++ (int) // p
  • stx
form
  • f
incremen t f // clone, up date, return clone deque<T>::iterato r clone(theDeque, index); index++; return clone; g Ha ving describ ed the structure
  • f
deque iterators, w e can no w return to the description
  • f
those deque metho ds that mak e use
  • f
iterators. The metho d erase reco v ers the index p
  • sition
from the iterator, and erases an elemen t from the appropriate v ector. It uses the fact that v ectors construct random access iterators, and so w e can easily create the iterator that corresp
  • nds
to a giv en index p
  • sition
within a v ector. template <class T> void deque<T>::erase (deque<T>::iterat
  • r
& itr) // erase v alue from deque f int index = itr.index; int n = vecOne.size (); if (index < n) vecOne.erase (vecOne.begin () + ((n-1)
  • index));
else vecTwo.erase (vecTwo.begin () + (n
  • index));
g The insert metho d is similar, and will not b e sho wn. The erase metho d that remo v es a range
  • f
v alues is more complicated, since the range ma y cross the b
  • undary
b et w een the t w
  • v
ectors. The implemen tation
  • f
this metho d therefore divides in to three cases, dep ending up
  • n
whether all the elemen ts to b e remo v ed are in the rst v ector, are all in the second v ector,
  • r
whether some are in the rst v ector and some are in the second. The dev elopmen t
  • f
this co de will b e left as an exercise. 11.5 Chapter Summary Key Concepts
  • deque
  • Depth
rst searc h
slide-27
SLIDE 27 284 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES
  • Breadth
rst searc h
  • Bac
ktrac king
  • F
ramew
  • rk
  • Inheritance
  • virtual
mem b er functions The deque,
  • r
double-ended-queue, is a data structure that pro vides a com bination
  • f
features from b
  • th
the vecto r and list data t yp es. Lik e a vecto r, a deque is a randomly accessible and indexed data structure. Lik e a list, elemen ts can b e ecien tly inserted at either the fron t
  • r
the end
  • f
the structure. Th us a deque can b e used in either a stac k-lik e
  • r
a queue-lik e fashion. W e ha v e illustrated the use
  • f
the deque b y dev eloping a program that can nd a path through a simple maze. By storing the in termediate steps in a stac k, the searc h tec hnique will explore
  • ne
path en tirely to completion b efore examining alternativ es. This is kno wn as depth rst searc h. By c hanging the use
  • f
the deque to a queue-lik e form, all paths are explored in parallel. This is kno wn as br e adth rst searc h. W e ha v e in tro duced b acktr acking as a general problem solving tec hnique, applicable whenev er the \state"
  • f
the task at hand can b e captured and stored at the p
  • in
t where
  • ne
  • f
man y alternativ e p
  • ssibilities
m ust b e selected. Finally , w e in tro duced the idea
  • f
a soft w are fr amework. A framew
  • rk
describ es the general structure
  • f
a solution to a problem, without dening an y sp ecic details. These details can then b e lled in, t ypically using inheritance, to sp ecialize the framew
  • rk
for the solution
  • f
a giv en problem. A framew
  • rk
th us pro vides reuse not
  • nly
for co de but also for the reuse
  • f
an idea
  • r
approac h to solving a class
  • f
similar problems. Study Questions 1. Giv e a short c haracterization
  • f
the deque data t yp e. 2. What vecto r
  • p
erations are not supp
  • rted
b y the class deque? What list
  • p
erations? 3. Giv e the in teger enco ding
  • f
the follo wing simple six-cell maze: F S 4. Sho w the state
  • f
the deque in the maze example (Section 11.2) after v e mo v es ha v e b een p erformed.
slide-28
SLIDE 28 11.5. CHAPTER SUMMAR Y 285 5. Ho w do es breadth rst searc h dier from depth rst searc h? 6. What requiremen ts m ust b e satised in
  • rder
to use bac ktrac king in the solution
  • f
a problem? 7. What is a framew
  • rk?
8. What is the underlying represen tation used to hold the v alues in the implemen tation
  • f
the deque describ ed in this c hapter? Exercises 1. Consider the follo wing graph. Starting from no de A, list the v ertices as they migh t b e visited in a breadth rst searc h, and as they migh t b e visited using a depth rst searc h. Note that there are man y dieren t sequences for b
  • th
forms
  • f
searc h. A @ @
  • B
C E
  • @
@ J F D
  • G
@ @
  • I
H 2. The maze solving program exploits a redundancy in the maze enco ding. This re- dundancy come from the assumption that if
  • ne
can mo v e east from
  • ne
cell to the next,
  • ne
can also mo v e w est from the second cell bac k to the rst. The constructor maze::maze mak es use
  • f
this redundancy , b y
  • nly
pro cessing
  • p
enings to the north and w est. Ho w ev er, this redundancy is not in trinsic to the n umeric enco ding
  • f
the maze. A \one-w a y"
  • p
ening could easily b e describ ed as a cell with v alue 3, for example, b eing next to a call with v alue 7. F rom the 7 cell
  • ne
could mo v e to the 3 cell, but from the 3 cell
  • ne
could not mo v e bac k to the 7 cell. T
  • c
hange
  • ur
maze solving program it is
  • nly
necessary to c hange the constructor that translates the external enco ding in to the in ternal enco ding. Sho w the mo dications that m ust b e pro vided to p ermit this form
  • f
maze. 3. A dicult y
  • ccurs
when the rst elemen t is remo v ed from a deque, but the rst v ector in the in ternal represen tation is empt y . The p
  • p
then causes the rst elemen t to b e remo v ed from the second v ector. This is p
  • ten
tially costly if a n um b er
  • f
p
  • ps
are
slide-29
SLIDE 29 286 CHAPTER 11. DEQUES { DOUBLE ENDED D A T A STR UCTURES p erformed in sequence. A b etter alternativ e is to rst mo v e half the elemen ts from the second v ector in to the rst v ector, so that subsequen t p
  • ps
are implemen ted as
  • p
erations
  • n
the rst v ector. W rite implemen tations for p
  • p
front and p
  • p
back that use this idea. 4. The implemen tation
  • f
the erase metho d that tak es a range
  • f
v alues as argumen t m ust recognize three dieren t cases: (a) Both b eginning and end
  • f
range are found in the rst v ector. (b) Both b eginning and end
  • f
range are found in the second v ector. (c) Beginning
  • f
range is found in rst v ector, end
  • f
range in second v ector. Implemen t the co de for the erase metho d that handles eac h
  • f
these cases.