Non Deterministic Algorithms
Non Deterministic Algorithms
JACQUES COHEN
Physics Department, Brande~s Unwers~ty, Waltham, Massachusetts 02154
Prnmtive commands representing the concepts of choice, failure, and success are used to
describe non-deterministic algorithms for solving a variety of problems. First, the role of
the primitives is explained in a manner appealing to the reader's intuition. Then, a
solution to the classmal 8-queens problem is presented as a non-deterministic program,
and its implementation is described. Two examples follow, showing the usefulness of the
primitwes m computer-reded problem solving: the first is a simple question-answering
program, the other is a parser for a context-sensitive language. Finally, a brief survey of
current and related work is presented whmh includes: additmnal desLrable prumtives,
implementation, correctness, efficiency, and theoretical implicatmns
Keywords and Phrases: backtracking, language constructs, implementation, interpreters,
problem solving, efficiency.
CR Categories: 3.64, 4.13, 4.22, 5.23
Permission to copy without fee all or part of this material is granted provided that the copies are not made or
distributed for direct commercial advantage, the ACM copyright notice and the title of the pubhcation and its
date appear, and notice is given that copying is by permission of the Association for Computing Machinery. To
copy otherwise, or to republish, requires a fee and/or specific permission.
© 1979 ACM 0010-4892/79/0600-0079 $00.75
1. AN INTUITIVE EXAMPLE
C o m p u t i n g S u r v e y s , V o l 11, N o 2, J u n e 1979
Non-Deterministic Algorithms 81
i start
time
0 - cho2ce point
FIGURE 1.
choices may involve more than two out- in charge of checking the desired sequence
comes. would obtain copies of himself at each
This example will illustrate our first choice point, the copies dispersing to the
problem: "Determine the plot leading to a halls where the next episodes would be
particular situation (say, one in which a shown. A copy would cease to exist in the
given character is shot, survives, and ends case of an impasse. Impasses occur when:
up eloping with the heroine)." 1) the movie ends and the sequence of
There are two approaches which could desired events has not occurred, or 2) an
be used to solve this problem, parallel and event occurs which directly contradicts the
sequential. desired sequence (say, in our example, if
In the first approach, the aid of a (poten- the character is shot and dies). T h e prob-
tially infinite) number of helpers for parallel lem is solved when a copy witnesses the
viewing is requested. Their duty is to watch specified sequence of events. We could even
for the occurrence of the particular se- ask him which projection halls he went
quence of events which interests us. If through while checking for the sequence. It
choice points take place before this occur- should be clear that for a specified sequence
rence, the helpers simply split up and dis- of events there may exist none, one, or
perse into the different halls to watch the several plots and therefore solutions to our
various sequels. Without the aid of the problem. Furthermore, if the projection
helpers, the parallel approach could only be lasts indefinitely, the number of solutions
used if we had the supernatural power to may be infinite.
obtain copies of ourselves. 1 The spectator T he solution of our problem using the
~ Incidentally, Sabine, t h e beautiful heroine of t h e
F r e n c h novelist Marcel A y m 6 h a d s u c h powers S h e In n a r r a t i n g w h a t h a p p e n s to t h e various S a b m e s ,
could obtain new copies of herself w h e n e v e r s h e de- A y m 6 h a d to face t h e p r o b l e m of describing non-
sired. In t h e novel, Sabine resorted to h e r d u p h c a t m g deterministic situations to a reader w h o sequentially
powers after falhng in love with t h e h a n d s o m e new s c a n s t h e text. Thin p r o b l e m parallels t h a t of translat-
lovers s h e h a d no trouble e n t m m g By t h e e n d of t h e ing a n o n - d e t e r m i n i s t i c a l g o r i t h m into one w h i c h is
novel t h e n u m b e r of Sablnes rose to t h e thousands! sequentially executed by a c o m p u t e r .
success;
(2, *, *, *), (3, *, *, *), and (4, *, *, *). These
are (partly) shown in the tree of Figure 3b. The following points are worth noting:
For each of the above configurations there 1) The board is assumed to be initially
are four possible ways of placing the second empty. The words choice, failure,
queen in the second column. Obviously the and success were intuitively defined
configurations (1, 1, *, *) and (1, 2, *, *) in the previous section.
represent a failure--no matter what digits 2) The tree of choices is inspected from
replace the asterisks. These nodes of the the root (col -- 1) towards the leaves
tree are labelled with an F. (col = 4).
The darker line in the figure shows the 3) The non-deterministic command
path in the tree of choices which leads to a p r i n t (row) consists of internally writ-
solution of the problem. The reader is urged ing the value of row. (This value may
to verify that the sequential approach for be erased if later, during the execu-
solving this problem involves inspecting the tion, the branch containing the p r i n t
tree nodes numbered 1, 2, 3, ...9. He may command is backtracked.) Notice that
also find it useful to complete the tree the value of c o l need not be printed
shown in Figure 3b. since it always increases from 1 to 4.
Although we have consistently repre- 4) The command success is only
sented the branches coming from each node reached after the cascading c h o i c e ' s
in ascending order, this is not strictly nec- are executed. At that point the printed
essary. Actually, the order in which the values of r o w reveal the solution of
branches are considered is irrelevant. This the problem.
Computing Surveys, VoL 11, No 2, June 1979
84 • J. Cohen
(*,*,*,*)
4,2,*) ,4,1,*)
\ ,\ j 2/ 31
1 2 3 4 F
// F
\F
./II \o
F F F --
~w I ~ (2,4,1,3)
2 ,g,
3 '~'' b
4 ~
( 2, 4, 2, 3 )
FIGURE 3.
A succinct version of the above program grams by using transformation rules. The
is obtained by using a for statement to rules may be found in FLOY67 and COHE75.
successively assign the values 1, 2, . . . etc. This presentation describes informally how
to the variable col. Our original 8-queens the translation is accomplished, using the
problem can then be described as the fol- 8-queens problem as an example.
lowing non-deterministic algorithm: The translated program operates in the
for col ~ 1 to 8 do sequential mode described in the first sec-
begin tion. Upon failure it backtracks to the pre-
choice a m o n g row *-- 1 to 8; vious choice point in a manner analogous
if T then place queen at (row, col) to the backward projection of movies.
else failure; When the statement i ~-- i + 1 is found in
p r i n t (row) a program, it is executed in the backward
end; direction as i ~-- i - 1, to undo what was
success;
originally performed. Another manner of
This formulation is at least as succinct and handling assignments is to save the value
perhaps more natural than the recursive of the variable just prior to the assignment,
algorithms which solve this problem (see and to restore it to that variable during the
DIJK72 and WIRT76). backward execution.
Let us consider a sequence of non-deter-
3. TRANSLATION INTO STANDARD
ministic commands S~, $2. . . . Sn. We will
PROGRAMS
indicate by S, + the translation of S, in the
forward mode, and by S,- the translation of
Non-deterministic algorithms can be trans- S, in the backtrack mode.
lated automatically into computer pro- The translation of the sequence into a
call t h a t this test is needed for checking if 5 yields as a result the 8-tuple (1,5,8,6,3,7,
a queen can be placed at a given row and 2,4) which corresponds to the first solution
column of the board.) of the problem (see Figure 2).
We note t h a t the sum of the indices of If we desired all successful configurations
each element in one left-right diagonal of a it would suffice to add a line consisting of
matrix representing the chessboard is the the statements:
same. This is also true for the differences 13) B (---false; ~ (---14; g o t o loop;
of indices in a right-left diagonal. Therefore,
T h e s e s t a t e m e n t s simulate an impasse by
two unidimensional Boolean arrays b and triggering the backtrack mode and transfer-
c can be used to test for the existence of ring control to col (--- col - i in line 9.
queens in the diagonals. A third Boolean
a r r a y a is used to indicate the presence of
a queen in a row. T h e bounds of a, b, and 4. VARIANTS OF THE CHOICE COMMAND
c are respectively: 1:8, 2:16 (i.e., the range In the previous section the c h o i c e com-
of the sum of the indices of matrix ele- m a n d a p p e a r e d in a form which only al-
ments) and - 7 : 7 (i.e., the range of the dif- lowed a controlled variable x to be succes-
ferences of indices). T h e arrays are initial- sively assigned values from 1 to n. In this
ized to f a l s e . T h e presence of a queen in a section we will describe more versatile ver-
row or diagonal is indicated by setting the sions of c h o i c e . Consider the database con-
corresponding e l e m e n t of an array to t r u e . sisting of the lists:
T e s t T t h e n becomes:
(CLIMATE ECUADOR T E M P E R A T E )
(a[row] V b[row + col] V c[row - col]) (SOIL U R U G U A Y FERTILE)
According to this data structure, the place- (CLIMATE UR UGUA Y T E M P E R A T E )
m e n t of a queen in a row is represented by: (SOIL ECUADOR B A R R E N )
(CLIMATE P A R A G U A Y T E M P E R A T E )
(SOIL P A R A G U A Y FERTILE)
a[row] (-- b[row + col] (--- c[row - col] (-- (GROWS P A R A G U A Y WHEAT)
true (GROWS ECUADOR CACTUS)
Its backtracking c o u n t e r p a r t is therefore: T h e above list contains geographical infor-
a[row] (--- b[row + col] (-- c[row - col] (-- m a t i o n a b o u t Latin American countries,
false and has been used by Carbonell to illustrate
Keeping the information given in the pre- his question-answering program (see
vious paragraphs in mind, the reader should BOBR74).
have no difficulty in understanding the pro- An interesting variant of the c h o i c e com-
gram in Figure 5. It corresponds to the m a n d appears u n d e r the disguise of a
translation of our original non-determinis- search. Consider the two commands:
tic algorithm. search (CLIMATE x T E M P E R A T E )
T h e execution of the program in Figure search (SOIL x F E R T I L E )
5) i f a [row] V b [row+col] k/ c [ r o w - c o l ] I
0 t h e n backtrack ! no operatton,
7) a[row]*-b[row+col]*-c[row-col]*-true ! a[row]*-b[row+col]*-c[row-col]*-false,
8) stack W (row) ~ u n s t a c k W,
9) col(-col+l I col*-col-1,
W) t*--1 I
e
end o f case ;
11) i ~--1 + (if B t h e n 2 e l s e - 2); g o t o loop ;
12) success • p r t n t W ;
FIGURE 5.
These commands request binding the vari- c h o i c e is re-entered in the backtrack mode,
able x to a country in the database such it proceeds from where it had left off; how-
that both searches are satisfied. In other ever, care must be taken to fncst undo the
words, these commands correspond to de- tasks performed during the latest activa-
termining a country (or countries) with tion. The example below illustrates the po-
temperate climate and fertile soil. A non- tentially intricate control structure which
deterministic situation arises because there results from using the o r c h o i c e command.
is a choice for binding x when satisfying the Consider the following program in which
first search. If the sequential approach is the S,'s are basic commands:
used, x is initially bound to E C U A D O R . $1;
When the second search is attempted a orchoice Se $3 $4;
failure occurs since that country has a bar- $5;
ren soil.
Backtracking takes place, the first search Let us, as before, denote by S, + the execu-
is resumed and x is now bound to URU- tion of S, in the forward mode and S,- the
G U A Y . This binding is satisfied by the corresponding execution in the backtrack
second search. Had we wished to check if mode. Assume that sometime during the
the database contained other countries execution S, + leads to a backtrack mode;
which satisfied the two search commands, we will indicate this occurrence by the no-
we could, as in the case of the 8-queens, tation S~. The following sequences of S,'s
simulate a failure immediately after having show some of the possible flows of control
bound x to U R U G U A Y . This would enable while the above program is executed:
us to find P A R A G UA Y as another suitable S~(T $1- . . . (continues backtracking)
binding for x. $1+ S2+T$2~ S~+ S~+ . . . (contmues forward)
We will now informally describe a mini- $1+ $2÷ S~ $5- $2- $3÷ Ss+ " " (continues for-
language containing several features of lan- ward)
guages proposed for solving problems in 81 + 82+~ 82- S3+~ 83- S4 + 855 S5- $4- S l - . , ,
artificial intelligence [BoBR74]. Programs (continues backtracking)
written in this language may contain se- The translation of the search and or-
quences of search commands as illustrated c h o i c e commands into their deterministic
above. In addition, these sequences can be counterparts can be made in a manner sim-
grouped into procedures which may or may ilar to that described in Section 3. T h e
not have formal parameters and local vari- command search is really a variant of
ables. Calls of procedures are accomplished c h o i c e and is translated into calls of pro-
by a variant of choice, referred to as or- cedures fsearch and bsearch which parallel
choice. Its parameter is a list of searches fchoice and bchoice (see Figure 4). The
or procedures being called. Finally, we will translation of o r c h o i c e is slightly more
allow the o r c h o i c e command to appear complex: it involves simulating non-deter-
within the body of procedures. Recursive ministic subroutines. This is done by first
procedures are, of course, permitted. checking if a subroutine is to be executed
Both the commands search and or- in the forward or in the backtrack mode. If
c h o i c e embody properties of choice points. it is to be executed in the backtrack mode,
In the case of search, the set of possible control is transferred to "undo" the last
values consists of the lists contained in the statement of the subroutine; otherwise,
database which could be successfully control is transferred to the first statement
matched. The command o r c h o i c e greatly for normal forward execution. Details are
increases the power of the language, or- found in FLOY67.
c h o i c e , like search, successively tries a We are now ready to present a program
number of paths until it finds one leading which answers questions about crops grow-
to a successful situation. In this case, the ing in the countries described by the data-
paths represent the execution of the com- base given at the beginning of this section.
mands which are given as o r c h o i c e param- Consider, for example, the question:
eters. The o r c h o i c e command operates as W h a t grows in Uruguay? Notice that the
a backtrackable coroutine. Every time or- database does not explicitly contain the
a a b b C C
LEFT % 1 k 2 t 3--4~_~
% , , /I¢, % I
% % % j --
.J , ~ I /
I
\ % b t iI, "B~ ¢
/ l
! I ,,
~. ~ \ / I /
%' ~' "~" I #
~% % c I I
%. '% .,,
% -~ j /
%. f
,%. S //
F I G U R E 6.
proc parse;
begin
orchoice rulel rule2 rule3 rule4,
orchoice terminate parse;
e n d of parse;
proc terminate;
begin
search ( L E F T BIGS RIGHT);
success
end of terminate;
main: . . .
end
FIGURE 7.
SMIT73 SMITH, D. C., AND ENEA, H. J. "Back- Symp. Apphed Mathematws, Vol X,
tracking in MLISP2," in Proc Thtrd Int. American Mathematical Society, Provi-
Conf. Arttfictal Intelligence, 1973, 671- dence, R.I, 1960
685. WIRT76 WIRTH, N. Algorithms + data structures
WALK60 WALKER, R. J. "An enumerative tech- = programs, Prentme-Hall, Inc., Engle-
nique for a class of combinatorial prob- wood Cliffs, N.J., 1976. See also, Commun.
lems," m Combmatortal analysts; Proc. A C M 14, 4 (1971), 221-227.