?? The question of the eight Queens is an old and famous issue that was first proposed by international chess player Max Bessel (Max Bezzel) in 1848. The eight Queens question is described as: placing 8 queens on the chess of \ (8\times8\) so that they cannot attack each other, that is, any two queens cannot be on the same line, in the same column, or on the same slash, asking how many kinds of pendulum.
?? The eight Queens problem is a typical case of backtracking algorithms. This share uses induction to find all the solutions to the eight Queens problem, write in JavaScript, and learn about OOP in JavaScript.
?? The complete code for the eight Queens question is as follows:
<Html><Body><Script>//create a classfunction Eightqueen(arr,Cnt{ //parameters This.arr =Arr; This.CNT =Cnt; //methods This.Search = function(r){ //if r = = 8, then a solution is found if(r==8){ Document.Write(' <br> '+ This.CNT+' <br> '); This.Output( This.arr); This.CNT++; return NULL } for(varI=0;I<8;I++){ This.arr[R]=I;Flag= 1 for(varJ=0;J<R;J++){ //check If this position is valid if( This.arr[R]== This.arr[j]||R-J== Math.ABS( This.arr[R]- This.arr[j])){Flag= 0; Break; } } //IF flag = = 1, then the row numbered R is valid if(flag) This.Search(r+1); //search the next row } } //output The valid solutions in format This.Output = function(){ for(varI=0;I<8;I++){ for(varJ=0;J<8;J++){Pos=(j==Arr[i])? ' 1 ':' 0 '; Document.Write(POS); } Document.Write(' <br> '); } }}//initial ArrayvarArr=[-1,-1,-1,-1,-1,-1,-1,-1]//create A objectvareq= New Eightqueen(arr,1);//use object ' s method to find all solutions and print themeq.Search(0);</script></body></html>
In the JavaScript code above, first defines a class (class): Eightqueen, whose parameters are: arr,cnt, where arr is the initialized array, and CNT can count the methods. The method search () is defined in Eightqueen, the parameter is R (line R), and when R equals 8 o'clock, a valid solution is found, and the output () function is called to export the valid solution, and then the effective solution of the next row is found after finding the valid solution of the first R line. Using the parameter CNT can help us count, so we can find the number of all valid solutions.
?? The result of the code running in the Web page is as follows:
As you can see, the number of all valid solutions is 92.
?? Of course, in the HTML can use a better visual method to show, welcome interested students to try ~ ~
?? This share to the end, welcome to Exchange ~ ~
The eight Queens problem of JavaScript (induction)