Algorithms and Data Structures
Algorithms and Data Structures
Algorithms and Data Structures
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 113<br />
23 10 15 4 25<br />
16 5 24 9 14<br />
11 22 1 18 3<br />
6 17 20 13 8<br />
21 12 7 2 19<br />
23 4 9 14 25<br />
10 15 24 1 8<br />
5 22 3 18 13<br />
16 11 20 7 2<br />
21 6 17 12 19<br />
1 16 7 26 11 14<br />
34 25 12 15 6 27<br />
17 2 33 8 13 10<br />
32 35 24 21 28 5<br />
23 18 3 30 9 20<br />
36 31 22 19 4 29<br />
Table 3.1. Three Knights' Tours.<br />
What abstractions can now be made from this example? Which pattern does it exhibit that is typical for<br />
this kind of problem-solving algorithms? What does it teach us? The characteristic feature is that steps<br />
toward the total solution are attempted <strong>and</strong> recorded that may later be taken back <strong>and</strong> erased in the<br />
recordings when it is discovered that the step does not possibly lead to the total solution, that the step leads<br />
into a dead-end street. This action is called backtracking. The general pattern below is derived from<br />
TryNextMove, assuming that the number of potential c<strong>and</strong>idates in each step is finite.<br />
PROCEDURE Try;<br />
BEGIN<br />
IF solution incomplete THEN<br />
initialize selection of c<strong>and</strong>idates <strong>and</strong> choose the first one;<br />
WHILE ~(no more c<strong>and</strong>idates) & ~CanBeDone(c<strong>and</strong>idate) DO<br />
select next<br />
END<br />
END<br />
END Try;<br />
PROCEDURE CanBeDone (move): BOOLEAN;<br />
BEGIN<br />
record move;<br />
Try;<br />
IF not successful THEN<br />
cancel recording<br />
END;<br />
RETURN successful<br />
END CanBeDone<br />
Actual programs may, of course, assume various derivative forms of this schema. In particular, the way<br />
input is passed to TryNextMove may vary depending on the problem specifics. Indeed, this procedure<br />
accesses global variables in order to record the solution, <strong>and</strong> those variables contain, in principle, a<br />
complete information about the current state of the construction process. For instance, in the knight's tour<br />
problem TryNextMove needs to know the knight's last position on the board, which can be found by a<br />
search in the matrix h. However, this information is explicitly available when the procedure is called, <strong>and</strong> it<br />
is simpler to pass it via parameters. In subsequent examples we will see variations on this theme.<br />
Note that the search condition in the while loop is modeled as a procedure-function CanBeDone for a<br />
maximal clarification of the logic of the algorithm while keeping the program easily comprehensible.