To share the following is the backtracking method eight queen, with detailed annotation, here is not much nonsense.
function Nqueens {if (Order < 4) {Console.log (' N Queens problem apply to order bigger than 3!
');
Return
} var nqueens = [];
var backtracking = false; Rowloop:for (var row=0 row<order; row++) {//If the row is less than 0, the problem is no solution if (Row < 0) {Console.log (' This N Queens problem has no solution!
');
Break
///First detected a new row of if (nqueens[row] = = undefined) {Nqueens[row] = []; }//back-run block for (Var col=0. col<order; col++) {//0 for locations that have been detected and for which the Queen can be placed if (Nqueens[row][col)
= = = 0) {continue;
///backtracking process, where the queen can be placed, indicating that this position was not passed in the subsequent validation, and that it was necessary to process else if (backtracking && nqueens[row][col] = = 1) {
Backtracking found that the previous line is also at the end of the line, which needs to continue backtracking if (col = = order-1) {Resetrow (Nqueens, order, row);
row = Row-2;
Continue Rowloop;
//Backtracking line not yet to the end of the line, Mark 0, continue nqueens[row][col] = 0; BacKtracking = false;
Continue
//Place a queen nqueens[row][col] = 1;
Find a place where you can place the Queen and jump to the next line (only one queen on a line).
if (Isqueenvalid (Nqueens, Row, col)) {continue rowloop;
}//Every line should have a queen, to the end of the column has not found a suitable location, indicating that the Queen placed in front of a problem, need to backtrack!
else if (col = = order-1) {backtracking = true;
0 and 1 indicate that this position has been detected, so the bank should be cleared as undefined Resetrow (nqueens, order, row);
Minus 2 is because the end of the loop has a self addition, in fact, is back to the row row = Row-2;
Back to the outer loop, continue continue rowloop;
else {//not to row, continue detecting nqueens[row][col] = 0;
Continue
};
} return nqueens; ///backtracking, clears function Resetrow (nqueens, order, row) {for (var col=0; col<order; col++) {Nqueens[row][col] = u
ndefined; }//Detection location can place Queen function Isqueenvalid (nqueens, Row, col) {//row detection for (var i=0; i<col; i++) {if (Nqueens[row) [i] = = 1) {return falsE for (Var j=1 j<row+1; J + +) {//column detection upper left 45 degree 45 degree if (Nqueens[row-j][col]==1 | | (nqueens[row-j][col-j]==1) | | (nqueens[row-j][col+j]==1))
{return false;
} return true;
function PRINTQ (Queens) {for (var row=0; row<queens.length; row++) {var rowtext = ';
for (var col=0; col<queens.length; col++) {if (queens[row][col]===undefined) {Queens[row][col] = 0;
} rowtext = Rowtext + Queens[row][col] + ';
} console.log (Rowtext);
} var queens = Nqueens (8);
PRINTQ (Queens);
The above is the entire content of this article, I hope you can enjoy.