mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
Fixes #620
This commit is contained in:
@ -2,6 +2,7 @@ class NQueen {
|
|||||||
constructor (size) {
|
constructor (size) {
|
||||||
this.board = new Array(size).fill('.').map(() => new Array(size).fill('.'))
|
this.board = new Array(size).fill('.').map(() => new Array(size).fill('.'))
|
||||||
this.size = size
|
this.size = size
|
||||||
|
this.solutionCount = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
isValid ([row, col]) {
|
isValid ([row, col]) {
|
||||||
@ -25,18 +26,26 @@ class NQueen {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
placeQueen (row, col) {
|
||||||
|
this.board[row][col] = 'Q'
|
||||||
|
}
|
||||||
|
|
||||||
|
removeQueen (row, col) {
|
||||||
|
this.board[row][col] = '.'
|
||||||
|
}
|
||||||
|
|
||||||
solve (col = 0) {
|
solve (col = 0) {
|
||||||
// function to solve the board
|
if (col >= this.size) {
|
||||||
if (col >= this.size) { return true }
|
this.printBoard()
|
||||||
|
this.solutionCount++
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
for (let i = 0; i < this.size; i++) {
|
for (let i = 0; i < this.size; i++) {
|
||||||
if (this.isValid([i, col])) {
|
if (this.isValid([i, col])) {
|
||||||
this.board[i][col] = 'Q'
|
this.placeQueen(i, col)
|
||||||
|
this.solve(col + 1)
|
||||||
if (this.solve(col + 1)) { return true }
|
this.removeQueen(i, col)
|
||||||
|
|
||||||
// backtracking
|
|
||||||
this.board[i][col] = '.'
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,22 +53,11 @@ class NQueen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
printBoard () {
|
printBoard () {
|
||||||
// utility function to display the board
|
console.log('\n')
|
||||||
for (const row of this.board) {
|
for (const row of this.board) {
|
||||||
console.log(...row)
|
console.log(...row)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function main () {
|
export { NQueen }
|
||||||
const board = new NQueen(8)
|
|
||||||
|
|
||||||
board.printBoard()
|
|
||||||
console.log('\n')
|
|
||||||
|
|
||||||
board.solve()
|
|
||||||
|
|
||||||
board.printBoard()
|
|
||||||
}
|
|
||||||
|
|
||||||
main()
|
|
||||||
|
15
Backtracking/tests/NQueen.test.js
Normal file
15
Backtracking/tests/NQueen.test.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
import { NQueen } from '../NQueen'
|
||||||
|
|
||||||
|
describe('NQueen', () => {
|
||||||
|
it('should return 2 solutions for 4x4 size board', () => {
|
||||||
|
const _4Queen = new NQueen(4)
|
||||||
|
_4Queen.solve()
|
||||||
|
expect(_4Queen.solutionCount).toEqual(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should return 92 solutions for 8x8 size board', () => {
|
||||||
|
const _8Queen = new NQueen(8)
|
||||||
|
_8Queen.solve()
|
||||||
|
expect(_8Queen.solutionCount).toEqual(92)
|
||||||
|
})
|
||||||
|
})
|
Reference in New Issue
Block a user