1 var New Checkboard (8);//Initialize the chessboard for 8 Queens 2 check.getresult (0); The parameter represents 3 console.log (check.result.length) starting from the No. 0 step;//All qualifying paths are saved in the array result //Result: 92 Solution (There are 92 solutions to the problem of---8 queens)
1 //N Queen problem source code----(JavaScript language)2 //define the location of each node3 varNode =function(i, j) {4 This. i =i;5 This. J =J;6 }7 //generate a checkerboard based on N8 9 varCheckboard =function(n) {Ten This. Check = [ One ]; A for(vari = 0; I < n; i++) { - vartemp = [ - ]; the for(varj = 0; J < N; J + +) { - varnode =NewNode (i, j); - Temp.push (node); - } + This. Check.push (temp); - } + This. N =N; A This. Nodes = [ at ]; - This. result = [ - ]; - } - //Check that the path is enough to exist on that point - inCheckBoard.prototype.passable =function () { - varArray = This. Nodes; to //returns False if there are peers in the array, the same column, or a diagonal node + varObject1 = { - }, theObject2 = { *};//separate managers row and column $ for(vark = 0, length = array.length; K < length; k++) {Panax Notoginseng vari=array[k].i,j=ARRAY[K].J; - if((!object1[i]) && (!Object2[j])) { theObject1[i] =true; +OBJECT2[J] =true; A}Else { the return false; + } - } $ //for this step, the proof is not in the same row, nor in the same column $ //determine if you are on the same diagonal - //Determines whether the principle on the diagonal is whether the absolute value of the straight line slope with all points is 1 - the if(Array.Length > 1) { - vartop = Array[array.length-1];Wuyi for(vari = 0, length = array.length-1; i < length; i++) { the varK = (TOP.J-ARRAY[I].J)/(TOP.I-ARRAY[I].I);//Calculate slope - if(Math.Abs (k) = = = 1) { Wu return false; - } About } $ } - return true; - } -CheckBoard.prototype.getResult =function(i) { A //I represent a step that is being walked + if(i = = This. N) {//when the nth step is being taken, the board has been traversed once the varArray = [ - ]; $ for(vari = 0, length = This. nodes.length; i < length; i++) { the varIndex1 = This. nodes[i].i; the varIndex2 = This. nodes[i].j; theArray.push (NewNode (index1, Index2)); the } - This. Result.push (array); in}Else { the for(varj = 0; J < This. N; J + +) { the //pushes the current position into the stack About This. Nodes.push ( This. Check[i][j]); the if( This. Passable ()) Arguments.callee (i + 1); the This. Nodes.pop (); the } + } -}
4 Queens or 8 Queens solution algorithm--------(n Queen solution algorithm, JS implementation)