This article describes how to implement the N Queen question algorithm in JavaScript. The N Queen question refers to placing N queens on the NxN chess board, no two queens are in the same row, column, or diagonal line, so that they cannot attack each other. For more information, see
Puzzles
N Queen's question. Place N queens on the NxN chess board. no two queens are in the same row, column, or diagonal line, so that they cannot attack each other.
Policy
Backtracking method.
JavaScript solution
Take the eight queens question as an example:
The code is 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 If (nQueens [row] === undefined ){
NQueens [row] = [];
}
For (var col = 0; 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 NQueens [row] [col] = undefined;
}
}
Function isQueenValid (nQueens, row, col ){
For (var I = 0; I If (nQueens [row] [I] = 1 ){
Return false;
}
}
For (var j = 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 Var rowText = '';
For (var col = 0; col If (queens [row] [col] === undefined ){
Queens [row] [col] = 0;
}
RowText = rowText + queens [row] [col] + '';
}
Console. log (rowText );
}
}
Var queens = getNQueens (8 );
PrintQueens (queens );
Result
The code is as follows:
1 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 1
0 0 0 0 1 0 0
0 0 1 0 0 0 0
0 0 0 0 0 1 0
0 1 0 0 0 0 0
0 0 0 1 0 0 0