Eight Queens question:
On the Chess 8*8 Board, eight queens and Queen cannot eat each other, and the eight Queens attack route
There is a 45-degree slash for the column and row it is in.
For this problem, first determine the recursive input and output, as well as the termination conditions and methods. A recursive completion pair when
The forward Queen position is determined, and by traversing all the columns, find out all possible. Where the traversal of a column is used, the actual
Now backtracking.
Specific implementation methods, can be understood through code, and the idea of reference 8029122
The blogger of the reference blog is very good at representing the position of the eight queens, and it is very useful for reference.
==========[data structure]: eight queens ===========
[Recursive],[backtracking]
Include include include define n 8//Determine the Order of eight Queens
int queen[n]; Each row corresponds to the Queen position queen[rows Row] = number of columns col
int num = 0; Calculate the correct number of possible occurrences
Judging the current line, is the Queen's position reasonable
BOOL Isqueen (int row)
{
for (int i=0;i<row;i++)//Compare the current row queen position to the released Queen position
{
if (ABS (row-i) = = ABS (Queen[row]-queen[i]) | | queen[row] = = Queen[i])
Here is the intent: to determine if the current row queen position conflicts with the released Queen position (diagonal | | same column)
{
return false;
}
}
return true;
}
Solving functions
void Eightqueen (int row)
{
for (int col=0;col<n;col++)//column to be placed, traversal, backtracking
{
Queen[row] = col; //
if (Isqueen (row))//
{
if (row = = n-1)//Last column, recursive termination condition
{
num++; Possible situation
printf ("%d type:", num);
for (int i=0;i<n;i++) printf ("(%d,%d)", I,queen[i]);
printf ("\ n");
}
else Eightqueen (row + 1); Next line
}
}
}
int main ()
{
printf ("====welcome to Eightqueen ' s question====\n means: (number of rows, number of columns in the current row) \ n");
Eightqueen (0);//Call the solve function, responsible for printing the results
}
By using recursive backtracking method, the solution of eight Queens problem is realized by C language.