-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
823 lines (806 loc) · 46.2 KB
/
index.html
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BASIC HTML PAGE</title>
<style>
.container {
width: 1088px;
margin: auto;
}
p {
opacity: 0.7;
}
.bold {
opacity: 1;
}
.list li {
height: 29px;
}
.sub1 {
border: 1px solid black;
background-color: #858585;
opacity: 0.9;
border-radius: 10px;
}
.sub2 {
border: 1px solid black;
border-radius: 10px;
color: green;
font-size: 3;
}
.sub3 {
border: 1px solid black;
background-color: #858585;
opacity: 0.9;
border-radius: 10px;
margin-top: 20px;
padding: 17px 24px;
}
</style>
</head>
<body>
<div class="container">
<h1>Backtracking</h1>
<p>Backtracking is a form of recursion.</p>
<p>The usual scenario is that you are faced with a number of options, and you must choose one of these. After
you make your choice you will get a new set of options; just what set of options you get depends on what
choice you made. This procedure is repeated over and over until you reach a final state. If you made a good
sequence of choices, your final state is a goal state; if you didn't, it isn't.</p>
<p>Conceptually, you start at the root of a tree; the tree probably has some good leaves and some bad leaves,
though it may be that the leaves are all good or all bad. You want to get to a good leaf. At each node,
beginning with the root, you choose one of its children to move to, and you keep this up until you get to a
leaf. </p>
<p>You can backtrack to continue the search for a good leaf by revoking your most recent choice, and trying out
the next option in that set of options. If you run out of options, revoke the choice that got you here, and
try another choice at that node. If you end up at the root with no options left, there are no good leaves to
be found.</p><br>
<p style="height: 31px;">This needs an example.</p>
<img src="Image_root.png">
<ol class="list">
<li>Starting at Root, your options are A and B. You choose A.</li>
<li>At A, your options are C and D. You choose C.</li>
<li>C is bad. Go back to A.</li>
<li>At A, you have already tried C, and it failed. Try D.</li>
<li>D is bad. Go back to A.</li>
<li>At A, you have no options left to try. Go back to Root.</li>
<li>At Root, you have already tried A. Try B.</li>
<li>At B, your options are E and F. Try E.</li>
<li style="height:40px">E is good. Congratulations!</li>
</ol>
<div class="sub1">
<p style="padding:17px 24px;opacity:0.7">In this example we drew a picture of a tree. The tree is an
abstract model of the possible sequences of choices we could make. There is also a data structure called
a tree, but usually we don't have a data structure to tell us what choices we have. (If we do have an
actual tree data structure, backtracking on it is called depth-first tree searching.)</p>
</div>
<hr>
<h2>The backtracking algorithm.</h2>
<div class="sub2">
<font size="3">
<pre>boolean solve(Node n) {
if n is a leaf node {
if the leaf is a goal node, return true
else return false
} else {
for each child c of n {
if solve(c) succeeds, return true
}
return false
}
}
</pre>
</font>
</div>
<div class="sub3">
<p style="opacity:0.7;">Notice that the algorithm is expressed as a boolean function. This is essential to
understanding the algorithm. If solve(n) is true, that means node n is part of a solution--that is, node
n is one of the nodes on a path from the root to some goal node. We say that n is solvable. If solve(n)
is false, then there is no path that includes n to any goal node.</p>
</div>
<h2>How does this work?</h2>
<ul>
<li>If any child of n is solvable, then n is solvable.</li>
<li style="height:45px;">If no child of n is solvable, then n is not solvable.</li>
</ul>
<p>Hence, to decide whether any non-leaf node n is solvable (part of a path to a goal node), all you have to do
is test whether any child of n is solvable. This is done recursively, on each child of n. In the above code,
this is done by the lines</p>
<div class="sub2">
<pre>
for each child c of n {
if solve(c) succeeds, return true
}
return false
</pre>
</div>
<p>Eventually the recursion will "bottom" out at a leaf node. If the leaf node is a goal node, it is solvable;
if the leaf node is not a goal node, it is not solvable. This is our base case. In the above code, this is
done by the lines</p>
<div class="sub2">
<pre>if n is a leaf node {
if the leaf is a goal node, return true
else return false
}</pre>
</div><br>
<P style="height:42px;">The backtracking algorithm is simple but important. You should understand it thoroughly.
Another way of stating it is as follows:</P>
<ul style="padding-left: 15px;">
<li>
<h2>To search a tree:</h2>
<ol>
<li style="height:20px;">If the tree consists of a single leaf, test whether it is a goal node.</li>
<li>Otherwise, search the subtrees until you find one containing a goal node, or until you have
searched them all unsuccessfully.</li>
</ol>
</li>
</ul>
<h2>Non-recursive backtracking, using a stack</h2>
<p>Backtracking is a rather typical recursive algorithm, and any recursive algorithm can be rewritten as a stack
algorithm. In fact, that is how your recursive algorithms are translated into machine or assembly language.
</p>
<div class="sub2">
<pre>
boolean solve(Node n) {
put node n on the stack;
while the stack is not empty {
if the node at the top of the stack is a leaf {
if it is a goal node, return true
else pop it off the stack
}
else { if the node at the top of the stack has untried children
push the next untried child onto the stack
else pop the node off the stack
}
return false
}
</pre>
</div><br>
<p>Starting from the root, the only nodes that can be pushed onto the stack are the children of the node
currently on the top of the stack, and these are only pushed on one child at a time; hence, the nodes on the
stack at all times describe a valid path in the tree. Nodes are removed from the stack only when it is known
that they have no goal nodes among their descendents. Therefore, if the root node gets removed (making the
stack empty), there must have been no goal nodes at all, and no solution to the problem.</p>
<p> When the stack algorithm terminates successfully, the nodes on the stack form (in reverse order) a path from
the root to a goal node. </p>
<p> Similarly, when the recursive algorithm finds a goal node, the path information is embodied (in reverse
order) in the sequence of recursive calls. Thus as the recursion unwinds, the path can be recovered one node
at a time, by (for instance) printing the node at the current level, or storing it in an array.</p>
<p style="height:30px;">Here is the recursive backtracking algorithm, modified slightly to print (in reverse
order) the nodes along the successful path:</p>
<div class="sub2">
<pre>boolean solve(Node n) {
if n is a leaf node {
if the leaf is a goal node {
print n
return true
}
else return false
} else {
for each child c of n {
if solve(c) succeeds {
print n
return true
}
}
return false
}
}
</pre>
</div>
<h2>Keeping backtracking simple</h2>
<p>All of these versions of the backtracking algorithm are pretty simple, but when applied to a real problem,
they can get pretty cluttered up with details. Even determining whether the node is a leaf can be complex:
</p>
<p>for example, if the path represents a series of moves in a chess endgame problem, the leaves are the
checkmate and stalemate solutions</p>
<p>To keep the program clean, therefore, tests like this should be buried in methods. In a chess game, for
example, you could test whether a node is a leaf by writing a <b>gameOver method</b> (or you could even call
it
<b>isLeaf</b>). This method would encapsulate all the ugly details of figuring out whether any possible
moves
remain.
</p>
<p>Notice that the backtracking altorithms require us to keep track, for each node on the current path, which of
its children have been tried already (so we don't have to try them again). In the above code we made this
look simple, by just saying <b>for each child c of n.</b> In reality, it may be difficult to figure out what
the
possible children are, and there may be no obvious way to step through them. In chess, for example, a node
can represent one arrangement of pieces on a chessboard, and each child of that node can represent the
arrangement after some piece has made a legal move. How do you find these children, and how do you keep
track of which ones you've already examined?</p>
<p>The most straightforward way to keep track of which children of the node have been tried is as follows: Upon
initial entry to the node (that is, when you first get there from above), make a list of all its children.
As you try each child, take it off the list. When the list is empty, there are no remaining untried
children, and you can return "failure." This is a simple approach, but it may require quite a lot of
additional work.</p>
<p>There is an easier way to keep track of which children have been tried, if you can define an ordering on the
children. If there is an ordering, and you know which child you just tried, you can determine which child to
try next.</p>
<p> For example, you might be able to number the <b>children 1 through n,</b> and try them in numerical order.
Then, if
you have just tried <b>child k,</b> you know that you have already tried children 1 through <b>k-1,</b> and
you have not
yet tried children <b>k+1</b> through <b>n.</b> Or, if you are trying to color a map with just four colors,
you can always
try <b>red first, then yellow, then green, then blue.</b> If child yellow fails, you know to try child green
next.
If you are searching a maze, you can try choices in the order left, straight, right <b>(or perhaps north,
east,
south, west).</b></p>
<p>It isn't always easy to find a simple way to order the children of a node. <b>In the chess game example,</b>
you
might number your pieces (or perhaps the squares of the board) and try them in numerical order; but in
addition each piece may also have several moves, and these must also be ordered. You can probably find some
way to order the children of a node. If the ordering scheme is simple enough, you should use it; but if it
is too cumbersome, you are better off keeping a list of untried children.</p>
<h2>Example: Tree Search</h2>
<p>For starters, let's do the simplest possible example of backtracking, which is searching an actual tree. We
will also use the simplest kind of tree, a binary tree.</p>
<p> A binary tree is a data structure composed of nodes. One node is designated as the root node. Each node can
reference (point to) zero, one, or two other nodes, which are called its children. The children are referred
to as the left child and/or the right child. All nodes are reachable (by one or more steps) from the root
node, and there are no cycles. For our purposes, although this is not part of the definition of a binary
tree, we will say that a node might or might not be a goal node, and will contain its name. The first
example in this paper (which we repeat here) shows a binary tree.</p>
<p>Here's a definition of the BinaryTree class:</p>
<div class="sub2">
<pre>public class BinaryTree {
BinaryTree leftChild = null;
BinaryTree rightChild = null;
boolean isGoalNode = false;
String name;
BinaryTree(String name, BinaryTree left, BinaryTree right, boolean isGoalNode) {
this.name = name;
leftChild = left;
rightChild = right;
this.isGoalNode = isGoalNode;
}
}
</pre>
</div><br>
<p style="opacity:0.6;">Next we will create a TreeSearch class, and in it we will define a method makeTree()
which constructs the above binary tree.</p><br>
<div class="sub2">
<pre>
static BinaryTree makeTree() {
BinaryTree root, a, b, c, d, e, f;
c = new BinaryTree("C", null, null, false);
d = new BinaryTree("D", null, null, false);
e = new BinaryTree("E", null, null, true);
f = new BinaryTree("F", null, null, false);
a = new BinaryTree("A", c, d, false);
b = new BinaryTree("B", e, f, false);
root = new BinaryTree("Root", a, b, false);
return root;
}
</pre>
</div><br>
<p style="opacity:0.6;">Here's a main program to create a binary tree and try to solve it:</p>
<div class="sub2">
<pre>
public static void main(String args[]) {
BinaryTree tree = makeTree();
System.out.println(solvable(tree));
}
</pre>
</div><br>
<p style="height:25px;">And finally, here's the recursive backtracking routine to "solve" the binary tree by
finding a goal node.</p>
<div class="sub2">
<pre>static boolean solvable(BinaryTree node) {
/* 1 */ if (node == null) return false;
/* 2 */ if (node.isGoalNode) return true;
/* 3 */ if (solvable(node.leftChild)) return true;
/* 4 */ if (solvable(node.rightChild)) return true;
/* 5 */ return false;
}</pre>
</div><br>
<p style="height:20px;">Here's what the numbered lines are doing:</p>
<ol class="list" style="padding-left:20px;">
<li>If we are given a null node, it's not solvable. This statement is so that we can call this method with
the children of a node, without first checking whether those children actually exist.</li>
<li>If the node we are given is a goal node, return success.</li>
<li>See if the left child of node is solvable, and if so, conclude that node is solvable. We will only get
to this line if node is non-null and is not a goal node, says to</li>
<li>Do the same thing for the right child.</li>
<li>Since neither child of node is solvable, node itself is not solvable.</li>
</ol>
<p style="height:25px;">This program runs correctly and produces the unenlightening result true.</p>
<p>Each time we ask for another node, we have to check if it is null. In the above we put that check as the
first thing in solvable. An alternative would be to check first whether each child exists, and recur only if
they do. Here's that alternative version:</p>
<div class="sub2">
<pre>
static boolean solvable(BinaryTree node) {
if (node.isGoalNode) return true;
if (node.leftChild != null && solvable(node.leftChild)) return true;
if (node.rightChild != null && solvable(node.rightChild)) return true;
return false;
}
</pre>
</div><br>
<p>I think the first version is simpler, but the second version is slightly more efficient.</p>
<h2 style="height:20px;">What are the children?</h2>
<p>One of the things that simplifies the above binary tree search is that, at each choice point, you can ignore
all the previous choices. Previous choices don't give you any information about what you should do next; as
far as you know, both the left and the right child are possible solutions. In many problems, however, you
may be able to eliminate children immediately, without recursion. </p>
<p>Consider, for example, the problem of four-coloring a map. It is a theorem of mathematics that any map on a
plane, no matter how convoluted the countries are, can be colored with at most four colors, so that no two
countries that share a border are the same color.</p>
<p>To color a map, you choose a color for the first country, then a color for the second country, and so on,
until all countries are colored</p>
<p>There are two ways to do this:</p>
<ul class="list" style="padding-left: 15px;">
<li>Method 1. Try each of the four possible colors, and recur. When you run out of countries, check whether
you are at a goal node.</li>
<li>Method 2. Try only those colors that have not already been used for an adjacent country, and recur. If
and when you run out of countries, you have successfully colored the map.</li>
</ul>
<p>Let's apply each of these two methods to the problem of coloring a checkerboard. This should be easily
solvable; after all, a checkerboard only needs two colors.</p><br>
<p><b class="bold">boolean mapIsOK()</b><br>Used by method 1 to check (at a leaf node) whether the entire map is
colored
correctly.</p>
<p><b class="bold">boolean okToColor(int row, int column, int color)</b><br>by method 2 to check, at every node,
whether
there is an adjacent node already colored with the given color.</p>
<p><b class="bold">int[] nextRowAndColumn(int row, int column)</b><br>Used by both methods to find the next
"country"
(actually, the row and column of the next square on the checkerboard).</p>
<p>Here's the code for method 1:</p>
<div class="sub2">
<pre>
boolean explore1(int row, int column, int color) {
if (row >= NUM_ROWS)return mapIsOK();
map[row][column] = color;
for (int nextColor = RED; nextColor <= BLUE; nextColor++) {
int[] next = nextRowAndColumn(row, column);
if (explore1(next[0], next[1], nextColor)) return true;
}
return false;
}
</pre>
</div><br>
<p>And here's the code for method 2:</p><br>
<div class="sub2">
<pre>
boolean explore2(int row, int column, int color) {
if (row >= NUM_ROWS)return true;
if (okToColor(row, column, color)) {
map[row][column] = color;
for (int nextColor = RED; nextColor <= BLUE; nextColor++) {
int[] next = nextRowAndColumn(row, column);
if (explore2(next[0], next[1], nextColor)) return true;
}
}
return false;
}
</pre>
</div><br>
<p>Those appear pretty similar, and you might think they are equally good. However, the timing information
suggests otherwise:</p>
<center>
<table border="1">
<thead>
<tr>
<td></td>
<td style="background-color:darkgray ;">2 by 3 map</td>
<td style="background-color:darkgray ;">3 by 3 map</td>
<td style="background-color:darkgray ;">3 by 4 map</td>
</tr>
</thead>
<tbody>
<tr>
<td style="background-color:darkgray ;">Method 1:</td>
<td>60ms.</td>
<td>940ms.</td>
<td>60530ms.(1 minute)</td>
</tr>
<tr>
<td style="background-color:darkgray ;">Method 2:</td>
<td>0ms.</td>
<td>0ms.</td>
<td>0ms.</td>
</tr>
</tbody>
</table><br>
</center>
<p>The zeros in the above table indicate times too short to measure (less than 1 millisecond). Why this huge
difference? Either of these methods could have exponential growth. Eliminating a node automatically
eliminates all of its descendents, and this will often prevent exponential growth. Conversely, by waiting to
check until a leaf node is reached, exponential growth is practically guaranteed. If there is any way to
eliminate children (reduce the set of choices), do so!</p>
<h2>Debugging techniques</h2>
<p>Often our first try at a program doesn't work, and we need to debug it. Debuggers are helpful, but sometimes
we need to fall back on inserting print statements. There are some simple tricks to making effective use of
print statements. These tricks can be applied to any program, but are especially useful when you are trying
to debug recursive routines.</p><br>
<h4>Trick #1: Indent when you print method entries and exits</h4>
<p style="height:40px;">Often, the best debugging technique is to print every method call and return (or at
least the most important ones). You probably want to print, for each method, what parameters it came in
with, and what value it leaves with. However, if you just print a long list of these, it's hard to match up
method exits with their corresponding entries. Indenting to show the level of nesting can help.
</p>
<h4>Trick #2: Use specialized print methods for debugging.</h4>
<p style="height:40px;"> Don't clutter up your actual code more than you must. Also, remember that code inserted
for debugging purposes can itself contain bugs, or (in the worst case) can affect the results, so be very
careful with it.</p>
<p style="height:40px;">Here's our debugging code. For this trivial program, there's almost more debugging code
than actual code, but in larger programs the proportions will be better.</p>
<div class="sub2">
<pre>
static String indent = "";
static String name(BinaryTree node) {
if (node == null) return null;
else return node.name;
}
static void enter(BinaryTree node) {
System.out.println(indent + "Entering solvable(" + name(node) + ")");
indent = indent + "| ";
}
static boolean yes(BinaryTree node) {
indent = indent.substring(3);
System.out.println(indent + "solvable(" + name(node) + ") returns true");
return true;
}
static boolean no(BinaryTree node) {
indent = indent.substring(3);
System.out.println(indent + "solvable(" + name(node) + ") returns false");
return false;
}
</pre>
</div><br>
<p>To use this code, we modify solvable as follows:</p>
<div class="sub2">
<pre>
static boolean solvable(BinaryTree node) {
enter(node);
if (node == null) return no(node);
if (node.isGoalNode) return yes(node);
if (solvable(node.leftChild)) return yes(node);
if (solvable(node.rightChild)) return yes(node);
return no(node);
}
</pre>
</div><br>
<p>And we get these results:</p>
<pre>Entering solvable(Root)
| Entering solvable(A)
| | Entering solvable(C)
| | | Entering solvable(null)
| | | solvable(null) returns false
| | | Entering solvable(null)
| | | solvable(null) returns false
| | solvable(C) returns false
| | Entering solvable(D)
| | | Entering solvable(null)
| | | solvable(null) returns false
| | | Entering solvable(null)
| | | solvable(null) returns false
| | solvable(D) returns false
| solvable(A) returns false
| Entering solvable(B)
| | Entering solvable(E)
| | solvable(E) returns true
| solvable(B) returns true
solvable(Root) returns true
true
</pre>
<h4>Trick #3: Never discard your debugging statements.</h4>
<p>Writing debugging statements is programming, too. Often it's as much work to debug the debugging statements
as it is to debug the actual program. Once your program is working, why throw this code away?</p>
<p>Obviously, you don't want to print out all this debugging information from a program you are ready to submit
(or to turn over to your manager). You could comment out your debugging calls, but that can be a lot of
work. What's more, in the above example, you would have to replace every return(yes(node)) with
return(true), and every return(no(node)) with return false. With all these changes, you might introduce new
bugs into your program.</p>
<p>The simple solution is to make your debugging statements conditional. For example,</p>
<div class="sub2">
<pre>
static final boolean debugging = false;
static void enter(BinaryTree node) {
if (debugging) {
System.out.println(indent + "Entering solvable(" + name(node) + ")");
indent = indent + "| ";
}
}
static boolean yes(BinaryTree node) {
if (debugging) {
indent = indent.substring(3);
System.out.println(indent + "solvable(" + name(node) + ") returns true");
}
return true;
}
static boolean no(BinaryTree node) {
if (debugging) {
indent = indent.substring(3);
System.out.println(indent + "solvable(" + name(node) + ") returns false");
}
return false;
}
</pre>
</div><br>
<p>In industry, actual programs often have multiple flags to control different aspects of debugging. Don't worry
too much about making your code larger; modern compilers will notice that since the variable debugging is
final, it can never be true, and the controlled code will be discarded.</p>
<h4>Trick #4: Create an Exception.</h4>
<p>If an Exception is thrown, you can get information about just where it happened by sending it the message
printStackTrace(PrintStream). Since an Exception is an object like any other, you can create and throw your
own Exceptions. However, Java programmers don't always realize that you can create an Exception without
throwing it. For example, the following code</p>
<div class="sub2" style="padding:20px;">new Exception("Checkpoint Charlie").printStackTrace(System.out);</div>
<br>
<p>will print out a message something like this, and the program will then continue normally. That is, the above
code just acts like a print statement.</p>
<div class="sub2">
<pre>java.lang.Exception: Checkpoint Charlie
at TreeSearch.solvable(TreeSearch.java:53)
at TreeSearch.solvable(TreeSearch.java:57)
at TreeSearch.main(TreeSearch.java:72)
at __SHELL38.run(__SHELL38.java:16)
at bluej.runtime.ExecServer.suspendExecution(Unknown Source)</pre>
</div><br>
<hr>
<h3>Example: Cindy's Puzzle</h3>
<p>I call the following puzzle "Cindy's puzzle" for historical reasons. You have some number n of black marbles
and the same number of white marbles, and you have a playing board which consists simply of a line of 2n+1
spaces to put the marbles in. Start with the black marbles all at one end (say, the left), the white marbles
all at the other end, and a free space in between.</p>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td><img src="black-ball.png"></td>
<td><img src="black-ball.png"></td>
<td style="padding:30px;"></td>
<td><img src="white-ball.png"></td>
<td><img src="white-ball.png"></td>
</tr>
</tbody>
</table>
<p>The goal is to reverse the positions of the marbles:</p>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td><img src="white-ball.png"></td>
<td><img src="white-ball.png"></td>
<td style="padding:30px;"></td>
<td><img src="black-ball.png"></td>
<td><img src="black-ball.png"></td>
</tr>
</tbody>
</table><br>
<p style="opacity:1">The black marbles can only move to the right, and the white marbles can only move to the
left (no backing up). At each move, a marble can either:</p>
<ul>
<li>
Move one space ahead, if that space is clear, or
</li>
<li>
Jump ahead over exactly one marble of the opposite color, if the space just beyond that marble is clear.
</li>
</ul>
<p">For example, you could make the following sequence of moves:</p>
<center>
<table>
<tbody>
<tr>
<td style="padding:10px 30px;">
<h4>starting position:</h4>
</td>
<td>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td><img src="black-ball.png"></td>
<td><img src="black-ball.png"></td>
<td style="padding:30px;"></td>
<td><img src="white-ball.png"></td>
<td><img src="white-ball.png"></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="padding:10px 30px;">
<h4>Black moves ahead:</h4>
</td>
<td>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td><img src="black-ball.png"></td>
<td style="padding:30px;"></td>
<td><img src="black-ball.png"></td>
<td><img src="white-ball.png"></td>
<td><img src="white-ball.png"></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="padding:10px 30px;">
<h4>White jumps:</h4>
</td>
<td>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td><img src="black-ball.png"></td>
<td><img src="white-ball.png"></td>
<td><img src="black-ball.png"></td>
<td style="padding:30px;"></td>
<td><img src="white-ball.png"></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="padding:10px 30px;">
<h4>Black moves ahead:</h4>
</td>
<td>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td><img src="black-ball.png"></td>
<td><img src="white-ball.png"></td>
<td style="padding:30px;"></td>
<td><img src="black-ball.png"></td>
<td><img src="white-ball.png"></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="padding:10px 30px;">
<h4>Black jumps:</h4>
</td>
<td>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td style="padding:30px;"></td>
<td><img src="white-ball.png"></td>
<td><img src="black-ball.png"></td>
<td><img src="black-ball.png"></td>
<td><img src="white-ball.png"></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="padding:10px 30px;">
<h4>White moves ahead:</h4>
</td>
<td>
<table border="1" cellpadding="6px" align="center">
<tbody>
<tr bgcolor="grey">
<td style="padding:30px;"></td>
<td><img src="white-ball.png"></td>
<td><img src="black-ball.png"></td>
<td><img src="black-ball.png"></td>
<td><img src="white-ball.png"></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td align="center">
<h4>stuck!</h4>
</td>
</tr>
</tbody>
</table><br>
</center>
<p>The backtracking method is named solvable and returns a boolean. In solvable we shall need to check
whether we are at a leaf, which in this case means a position from which no further moves are possible.
This isn't so easy. </p>
<p>
Now to the program. The main program will initialize the board, and call a recursive backtracking
routine to attempt to solve the puzzle. The backtracking routine will either succeed and print out a
winning path, or it will fail, and the main program will have to print out the bad news.
</p>
<p>The backtracking method is named solvable and returns a boolean. In solvable we shall need to check
whether we are at a leaf, which in this case means a position from which no further moves are possible.
This isn't so easy. </p>
<p> Each possible move will result in a new board position, and these new board positions are the children
of the current board position. Hence to find the children of a node (that is, of a board position), we
need only find the possible moves from that node. Remember that it is also highly desirable to find an
ordering on these possible moves.</p>
<p>
Here it is time to stop and take thought. To make progress, we must analyze the game to some extent.
Probably a number of approaches would work, and what follows is based on the way I worked it out. If you
were to program this puzzle, you might find a different but equally valid approach.
</p>
<p>First, notice that if a marble has a move, that move is unique: if it can move ahead one square, then it
cannot jump. If it can jump, it cannot move ahead one square. This suggests that, to find the possible
moves, we might assign numbers to the marbles, and check each marble in turn. When we have looked at all
the marbles, we have looked at all the possible moves. This would require having a table to keep track
of where each marble is, or else somehow "marking" each marble with its number and searching the board
each time to find the marble we want. Neither alternative is very attractive. </p>
<p>
Next, notice that for a given board position, each marble occupies a unique space. Hence, instead of
talking about moving a particular marble, we can talk about moving the marble in a particular space. If
a move is possible from a given space, then that must be the only move possible from that space, because
if the marble in that space has a move, it is unique. There is a slight complication because not every
space contains a marble, but at least the spaces (unlike the marbles) stay in one place.
</p><br>
<p class="bold">Now we have a simpler ordering of moves to use in our program. Just check, in order,
the 2n+1 spaces of the board. For each space, either zero or one moves is possible. With this
understanding, we can write a boolean method canMove(int[] board, int position) which determines whether
a move is possible from the given position:</p>
<ul>
<li>If the position is empty, no move is possible;</li>
<li>If the position contains a black marble, the method checks for a move or jump to the right;</li>
<li>If the position contains a white marble, the method checks for a move or jump to the left.</li>
</ul>
<p>We write another method <b>int[] makeMove(int[] oldBoard, int position)</b> that will take a board and a
position, make a move from that position, and return as its value a new board. (We could write this
somewhat more efficiently by changing the old board, rather than creating a new one, but here we are
more concerned with simplicity.) In technical jargon, makeMove is "applicative" rather than "mutative."
</p>
<p>Along with <b>canMove and makeMove,</b> we are using methods <b>puzzleSolved and printBoard</b> with
meanings that should be obvious. With these methods, our central backtracking method can be written as
follows:</p>
<div class="sub2">
<pre>
boolean solvable(int[] board) {
if (puzzleSolved(board)) {
return true;
}
for (int position = 0; position < BOARD_SIZE; position++) {
if (canMove(board, position)) {
int[] newBoard = makeMove(board, position);
if (solvable(newBoard)) {
printBoard(newBoard);
return true;
}
}
}
return false;
}
</pre>
</div><br>
<p>Along with canMove and makeMove, we are using methods puzzleSolved and printBoard with meanings that
should be obvious.</p>
<P>.Here is some output from the program:</p>
<ol type="1" reversed>
<li style="color:blue;"><b style="color:black;">WHITE WHITE WHITE ______ BLACK BLACK BLACK</b></li>
<li style="color:blue;"><b style="color:black;">WHITE WHITE WHITE BLACK _____ BLACK BLACK</b></li>
<li style="color:blue;"><b style="color:black;">WHITE WHITE _____ BLACK WHITE BLACK BLACK</b></li>
<li style="color:blue;"><b style="color:black;">WHITE _____ WHITE BLACK WHITE BLACK BLACK</b></li>
<li style="color:blue;"><b style="color:black;">WHITE BLACK WHILE _____ WHITE BLACK BLACK</b></li>
<li style="color:blue;"><b style="color:black;">WHITE BLACK WHITE BLACK WHITE _____ BLACK</b></li>
<li style="color:blue;"><b style="color:black;">WHITE BLACK WHITE BLACK WHITE BLACK _____ </b></li>
<li style="color:blue;"><b style="color:black;">WHITE BLACK WHITE BLACK _____ BLACK WHITE</b></li>
<li style="color:blue;"><b style="color:black;">WHITE BLACK _____ BLACK WHITE BLACK WHITE</b></li>
<li style="color:blue;"><b style="color:black;">_____ BLACK WHITE BLACK WHITE BLACK WHITE</b></li>
<li style="color:blue;"><b style="color:black;">BLACK _____ WHITE BLACK WHITE BLACK WHITE</b></li>
<li style="color:blue;"><b style="color:black;">BLACK BLACK WHITE ______ WHITE BLACK WHITE</b></li>
<li style="color:blue;"><b style="color:black;">BLACK BLACK WHITE BLACK WHITE ______ WHITE</b></li>
<li style="color:blue;"><b style="color:black;">BLACK BLACK WHITE BLACK ______ WHITE WHITE</b></li>
<li style="color:blue;"><b style="color:black;">BLACK BLACK ______ BLACK WHITE WHITE WHITE</b></li>
<li style="color:blue;"><b style="color:black;">BLACK BLACK BLACK ______ WHITE WHITE WHITE</b></li>
</ol>
<br>
<div class="sub2">
<p style="padding:10px;">Notice that the solution is given in reverse order: BLACK starts out on the
left and WHITE on the right, as in the last line. I've added line numbers to the actual output in
order to emphasize this point. Backtracking always produces its results (sequence of choices) in
reverse order; it is up to you, the programmer, to reverse the results again to get them in the
correct order.</p>
</div>
</div>
</body>
</html>