Skip to content

Instantly share code, notes, and snippets.

@blacksheep557
Created March 8, 2021 04:02
Show Gist options
  • Select an option

  • Save blacksheep557/64a2addcd5d093884d299cd90db83183 to your computer and use it in GitHub Desktop.

Select an option

Save blacksheep557/64a2addcd5d093884d299cd90db83183 to your computer and use it in GitHub Desktop.
function canBePlaced(board, x, y, n) {
//rows above the current column
for (let row = 0; row < y; row++) {
if (board[row][x]) return false
}
let row = y;
let col = x;
// upper-left diagonal
while (row >= 0 && col >= 0) {
if (board[row][col]) return false
row--
col--
}
row = y;
col = x;
// upper-right diagonal
while (row >= 0 && col < n) {
if (board[row][col]) return false
row--
col++
}
return true
}
function solveQueens(board, y, n) {
// base condition
if (y >= n) return true;
for (let col = 0; col < n; col++) {
if (canBePlaced(board, col, y, n)) {
board[y][col] = 1
if (solveQueens(board, y + 1, n)) return true
else board[y][col] = 0
}
}
return false
}
function generateBoard(n) {
let board = []
for (let i = 0; i < n; i++) {
board.push(new Array(n).fill(0))
}
return board
}
function main(n) {
let board = generateBoard(n);
console.log(solveQueens(board, 0, n))
console.log(board)
}
main(30)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment