Puzzles
n Queens question. Place n Queens on the NXN chess board, where no two queens are on the same line, the same column, or the same diagonal so that they cannot attack each other.
Strategy
Backtracking method.
JavaScript solution
Take the 8 queen question as an example:
Copy Code code as follows:
/**
* Created by Cshao on 12/28/14.
*/
function Getnqueens (order) {
if (Order < 4) {
Console.log (' N Queens problem apply for order bigger than 3 ');
Return
}
var nqueens = [];
var backtracking = false;
Rowloop:
for (var row=0; row<order; row++) {
if (nqueens[row] = = undefined) {
Nqueens[row] = [];
}
for (var col=0; col<order; col++) {
if (nqueens[row][col] = = 0) {
Continue
else if (backtracking && nqueens[row][col] = = 1) {
if (col = = order-1) {
Resetrow (Nqueens, order, row);
row = Row-2;
Continue Rowloop;
}
Nqueens[row][col] = 0;
backtracking = false;
Continue
}
Nqueens[row][col] = 1;
if (Isqueenvalid (Nqueens, Row, col)) {
Continue Rowloop;
else if (col = = order-1) {
backtracking = true;
Resetrow (Nqueens, order, row);
row = Row-2;
Continue Rowloop;
} else {
Nqueens[row][col] = 0;
Continue
};
}
}
return nqueens;
}
function Resetrow (nqueens, order, row) {
for (var col=0; col<order; col++) {
Nqueens[row][col] = undefined;
}
}
function Isqueenvalid (nqueens, Row, col) {
for (var i=0; i<col; i++) {
if (nqueens[row][i] = = 1) {
return false;
}
}
for (Var j=1 j<row+1; J + +) {
if (Nqueens[row-j][col]==1 | | (nqueens[row-j][col-j]!=undefined && nqueens[row-j][col-j]==1) | | (nqueens[row-j][col+j]!=undefined && nqueens[row-j][col+j]==1)) {
return false;
}
}
return true;
}
function Printqueens (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 = Getnqueens (8);
Printqueens (Queens);
Results
Copy Code code as follows:
1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0