|
/ * This program uses the "exhaustive method" to solve the eight queens problem. File name BHH.C TC2.0 debug passed * /
/ * Set an 8 * 8 chessboard as shown below: * /
/ * 1 2 3 4 5 6 7 8 * /
/ * 1: 0 0 0 0 0 0 0 0 * * /
/ * 2: 0 * 0 0 0 0 0 0 0 * /
/ * 3: 0 0 0 * 0 0 0 0 * /
/ * 4: * 0 0 0 0 0 0 0 0 * /
/ * 5: 0 0 0 0 0 0 0 * 0 * /
/ * 6: 0 0 0 0 * 0 0 0 * /
/ * 7 : 0 0 * 0 0 0 0 0 * /
/ * 8: 0 0 0 0 0 0 * 0 0 * /
/ * An 8-bit sequence can be used to indicate the position of 8 queens, such as "82417536", which means to sequentially list the sequence number of the queen's column in each row * /
/ * The question is translated into the following two points: * /
/ * 1. Generate an 8-bit sequence P and make each number in the sequence not duplicate, that is to ensure different columns (different rows can be avoided when defining the sequence). * /
/ * 2. Find a sequence in the sequence that satisfies (1), so that the absolute value of the difference between any two digits in the sequence is not equal to their sequence number * /
/ * The absolute value of the difference, that is, there are no two queens on the same diagonal of the board. * /
/ * All sequences satisfying (2) are solutions to the eight queens problem. * /
#include <stdio.h>
#include <math.h>
#define N 8 / * Define the size of the board by adjusting the value of N * /
void check (int p []) / * The function check is used to check whether the sequence P satisfies (2) * /
{int i, j;
for (i = 0; i <N-1; i ++)
for (j = i + 1; j <N; j ++)
if (abs (p [j] -p [i]) == j-i) return; / * If it is not satisfied, return to the function permute and continue to find the next P * /
for (printf (""), i = 0; i <N; printf ("% d", p [i ++])); / * print the result of the sequence satisfying (2) * /
}
/ * Function permute uses recursion to find the sequence P satisfying (1) * /
void permute (int n, int p []) / * n means the current line has been found (set up from line 8), use P [] to save the sequence * /
{int i, j;
if (n == 1) check (p);
for (i = 0, j = n-1; i <N; i ++) / * Find the next row where the queen can be placed (P [i]! = 0) corresponding to the column i that has been dropped * /
if (! p [i]) {p [i] = j; permute (j, p); p [i] = 0;}
}
main ()
{int p [N] = {0}, n = N; / * Define the array p [N] to store the result sequence, n is the line number * /
printf ("\n");
permute (n + 1, p); / * call permute function to search * /
} |
|