The model of the backtracking algorithm is X + +, not satisfy? x--: Continue.
In the code x as the column number, y[x] Save the position of the Queen placed on column x.
1#include <stdio.h>2#include <math.h>3 #defineN 54 intPosition_check (int,int*);5 voidPrint_board (intCountint*y);6 intMain ()7 {8 inty[n]= {0};//record the position of the Queen placed on each column9 intCount =0;//Number of solutionsTen intx =1; One while(x>0) A { -y[x]++;//find the location of a queen for the current x position - while((y[x]<=n) &&!Position_check (x, y)) they[x]++;//find the right queen. - // - if(y[x]<=n)//find a place where you can place the X-Queens, and until that step, the partial solution satisfies the requirements . - { + if(x==n)//Find a complete placement scenario - { +count++; Aprintf"%d\n", count); at for(intI=1; i<=n; i + + ) - { - for(intj=1; j<=n; J + + ) - if(J==y[i]) printf ("x");//If the Queen is placed in that position, the X is displayed - Elseprintf"o"); -printf"\ n"); in } - } to Else +x + +;//continue to find the next Queen's position, not yet found the complete solution - } the Else//Could not find the place to put the X-Queen, until that step, already know that the requirements are not met * { $Y[X] =0;//because to backtrack, the next time is to find the position of the X-1 queen,Panax Notoginseng //After the next determination of the location of the x-1, the position of the beginning of the first x Queen is reset -x--;//Backtracking the } + } A } the intPosition_check (intKint* y)//test Legitimacy + { - for(intj =1; J < K; J + +) $ if(ABS (K-J) = = ABS (Y[j]-y[k])) | | (Y[j] = =Y[k])) $ return 0; - return 1; -}View Code
See Tang Dashi Teacher's 8 queen changed, basically is copy paste (╯-╰)
C-Language backtracking algorithm solves the problem of n Queens