I accidentally figured out the recursive-Backtracking Method I wrote N years ago to solve the problem of eight queens. Let's stick it to my blog.
# Include <stdio. h> <br/> # include <conio. h> <br/> # include <math. h> </P> <p> # define queens 8 </P> <p> // global variable that records the sequence number of the solution. <Br/> int icount = 0; </P> <p> // records the position of the queen in a Global Array of columns. <Br/> int site [queens]; </P> <p> // recursive function. <Br/> void Queen (int n); </P> <p> // output a solution. <Br/> void output (); </P> <p> // determine whether conflict exists after the nth queen is put. <Br/> int isvalid (int n); </P> <p> void main () <br/>{< br/> // recursive testing starts from column 0th. <Br/> Queen (0); <br/>}</P> <p> // queen: recursively places the nth queen. <Br/> void Queen (int n) <br/>{< br/> int I; </P> <p> // parameter n starts from 0, when it is equal to 8, a solution is created, which is output and traced back. <Br/> If (n = queens) <br/>{< br/> output (); <br/> return; <br/>}</P> <p> // n has not reached 8. Test the rows in column N in sequence. <Br/> for (I = 1; I <= Queens; I ++) <br/>{< br/> // place the Queen on row I of the column. <Br/> site [N] = I; </P> <p> // if no conflict exists, test the next column. <Br/> If (isvalid (N) <br/> Queen (n + 1 ); <br/>}</P> <p> // isvalid: determines whether the n-th queen is legal after it is put, that is, whether there is no conflict. <Br/> int isvalid (int n) <br/>{< br/> int I; </P> <p> // compare the positions of the n-th queen with those of the n-th queen. <Br/> for (I = 0; I <n; I ++) <br/> {<br/> // The two queens return 0 on the same row. <Br/> If (site [I] = site [N]) <br/> return 0; </P> <p> // The two queens are on the same diagonal line, returns 0. <Br/> If (ABS (site [I]-site [N]) = (n-I) <br/> return 0; <br/>}</P> <p> // no conflict exists. 1 is returned. <Br/> return 1; <br/>}</P> <p> // output: outputs a solution, that is, a placement scheme without conflict. <Br/> void output () <br/>{< br/> int I; </P> <p> // output sequence number. <Br/> printf ("no. %-5d ", ++ icount); </P> <p> // output the location of the Queen on each column in sequence, that is, the number of rows. <Br/> for (I = 0; I <Queens; I ++) {<br/> printf ("% d", site [I]); <br/>}</P> <p> printf ("/N"); <br/>}< br/>
This algorithm is used to find 92 la S. But they are not an essential solution, so some of the output la s are equivalent after rotation, image, and other transformations.
If the essential solution is required (there should be only 12 types), you can consider placing the obtained layout in a linked list, and then each time you get a new layout, compare them with the previous ones to see if the images are consistent after rotation. If they are the same, discard them.