Home >Web Front-end >JS Tutorial >JavaScript implementation of N Queens problem algorithm puzzle solution_javascript skills
Puzzle
N Queen problem. Place N queens on an NxN chess board where no two queens are in the same row, column or diagonal so that they cannot attack each other.
Strategy
Backtracking method.
JavaScript Solution
Take the 8 Queens problem as an example:
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
nQueens[row] = [];
}
for (var col=0; col
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
}
}
function isQueenValid(nQueens, row, col) {
for (var i=0; i
function printQueens(queens) {
for (var row=0; row
for (var col=0; col
Queens[row][col] = 0;
}
rowText = rowText queens[row][col] ' ';
}
console.log(rowText);
}
}
var queens = getNQueens(8);
printQueens(queens);
Results