Created
March 8, 2021 04:02
-
-
Save blacksheep557/64a2addcd5d093884d299cd90db83183 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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