Backtracking algorithm :
【Question Frame】
Suppose the solution of the problem is an n-dimensional vector (a1, a2, ......, an), and the constraint condition is that ai (i=1, 2, 3, ....., n) satisfies a certain condition, denoted as f (ai).
begin
for i:=1 to operator types Do {operator: enumerate all paths}
begin
save results
if to destination then output solution
else Try(k+1);
restore: save the state before the result {backtrack one step}
end;
end;
Example 1: The Eight Queens Problem:
The algorithm for placing the ith queen is: (recursive algorithm)
procedure Try(i);
begin
if i>8 then output a set of results; exit ; (choose from the red part below)
for the position of the ith queen = 1 to 8 do
if safe then
begin
place the i-th queen;
Mark the position where the queen is placed;
if i=8 then 输出 else
Try(i+1); {place i+1 queen}
Release the marker on the position where the queen is placed, try the next position
end;
end;
Example 2: There is a set of n integers {1,2,…,n}, take out any r numbers for permutation (r<n), and try to list all permutations.
type se=set of 1..100;
VAR s: se; n, r, num: integer;
b:array [1..100] of integer;
PROCEDURE print;
var i: integer;
begin
num:=num+1;
for i:=1 to r do write(b[i]:3);
writeln;
end;
PROCEDURE try(k:integer);
VAR i: integer;
begin
for i:=1 to n do
if i in s then
begin b[k]:=i; s:=s-[i];
if k=r then print else try(k+1);
s:=s+[i];
end;
end;
BEGIN {main}
write('Input n,r:');readln(n,r);
s:=[1..n];num:=0;
try(1);
writeln('number=',num);
END.