Академический Документы
Профессиональный Документы
Культура Документы
When invoked, the algorithm starts with an empty vector. At each stage it extends the partial
vector with a new value. Upon reaching a partial vector (v1, ..., vi) which can’t represent a partial
solution, the algorithm backtracks by removing the trailing value from the vector, and then
proceeds by trying to extend the vector with alternative values.
ALGORITHM try(v1,...,vi)
IF (v1,...,vi) is a solution THEN RETURN (v1,...,vi)
FOR each v DO
IF (v1,...,vi,v) is acceptable vector THEN
sol = try(v1,...,vi,v)
IF sol != () THEN RETURN sol
END
END
RETURN ()
If Si is the domain of vi, then S1 × ... × Sm is the solution space of the problem. The validity
criteria used in checking for acceptable vectors determines what portion of that space needs to
be searched, and so it also determines the resources required by the algorithm.
Problem Statement:
Algorithm:
Algorithm SumOfSubs(s, k, r)
S[k]:=1;
Else if(s+w[k]+w[k+1<=m])
x[k]:=0;
Class Work:
Problem Statement:
#include<stdio.h>
#include<conio.h>
#include<math.h>
int X[100];
int i;
int place(int k) ;
void n_queens(int n) ;
void main()
{
clrscr();
int q;
getch();
int place(int k)
{
int i;
for(i=1; i<=k-1; i++)
{
if(X[i]==X[k])
{
return 0;
}
else if(abs(X[i]-X[k])==abs(i-k))
{
return 0;
}
}
return 1;
}
void n_queens(int n)
{
while(k>0)
{
X[k]=X[k]+1;
if(X[k]<=n-1)
{
if(k==n-1)
{
int j;
for(j=1;j<n;j++)
{
printf("%d ", X[j]);
}
printf("\n");
}
else
{
k=k+1;
X[k]=0;
}
}
else
{
k=k-1;
}
}
Source-code: solve of n-queens with mirror solutions elimination
#include<stdio.h>
#include<conio.h>
#include<math.h>
int X[100];
int i;
int place(int k) ;
void n_queens(int n) ;
void main()
{
clrscr();
int q;
getch();
}
int place(int k)
{
int i;
for(i=1; i<=k-1; i++)
{
if(X[i]==X[k])
{
return 0;
}
else if(abs(X[i]-X[k])==abs(i-k))
{
return 0;
}
}
return 1;
}
void n_queens(int n)
{
int k=1;//current row
X[1]=0;
while(k>0)
{
X[k]=X[k]+1;
if(X[k]<=n-1)
{
if(X[1]>n/2)
{
k=k+1;
X[k]=0;
}
else if(k==n-1)
{
int j;
for(j=1;j<n;j++)
{
printf("%d ", X[j]);
}
printf("\n");
}
else
{
k=k+1;
X[k]=0;
}
}
else
{
k=k-1;
}
}
}
Discussion:
Backtracking is a general algorithm for finding all (or some) solutions to some computational
problem that incrementally builds candidates to the solutions, and abandons each partial candidate c
("backtracks") as soon as it determines that c cannot possibly be completed to a valid solution. That’s how
the sum of subsets and n-queens problem was solved. As there arrives a condition that defines the
possible solution doesn’t exist in the current path, backtracking takes it to the previous step to find a path
that could hold a possible solution.
Backtracking