Skip to content

Instantly share code, notes, and snippets.

@sagartalla
Created July 12, 2019 15:11
Show Gist options
  • Save sagartalla/94a68f8a7adbe63a859b7c03c040e57a to your computer and use it in GitHub Desktop.
Save sagartalla/94a68f8a7adbe63a859b7c03c040e57a to your computer and use it in GitHub Desktop.
N queens
/*
Eight Queens:Write an algorithm to print all ways of arranging eight queens on an 8x8 chess board
so that none of them share the same row, column, or diagonal. In this case, "diagonal" means all
diagonals, not just the two that bisect the board.
*/
var GRID_SIZE = 4;
function check(board, r1, c1) {
for(var r2 = 0; r2 < r1; r2++) {
var c2 = board[r2];
if(c2 === c1) {
return false;
}
if((r1 - r2) === Math.abs(c1 - c2)) {
return false
}
}
return true;
}
function NQ(r, board = [], results = []) {
if(r === GRID_SIZE) {
results.push([...board]);
board = [];
}
for(var c = 0; c < GRID_SIZE; c++) {
if(check(board, r, c)) {
board[r] = c;
NQ(r+1, board, results);
}
}
}
var results = [];
NQ(0, [], results);
console.log('results', results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment