Skip to content

Commit e9fd4a9

Browse files
committed
1 parent a9b1f89 commit e9fd4a9

File tree

2 files changed

+34
-21
lines changed

2 files changed

+34
-21
lines changed

Backtracking/NQueen.js

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ class NQueen {
22
constructor (size) {
33
this.board = new Array(size).fill('.').map(() => new Array(size).fill('.'))
44
this.size = size
5+
this.solutionCount = 0
56
}
67

78
isValid ([row, col]) {
@@ -25,41 +26,38 @@ class NQueen {
2526
return true
2627
}
2728

29+
placeQueen (row, col) {
30+
this.board[row][col] = 'Q'
31+
}
32+
33+
removeQueen (row, col) {
34+
this.board[row][col] = '.'
35+
}
36+
2837
solve (col = 0) {
29-
// function to solve the board
30-
if (col >= this.size) { return true }
38+
if (col >= this.size) {
39+
this.printBoard()
40+
this.solutionCount++
41+
return true
42+
}
3143

3244
for (let i = 0; i < this.size; i++) {
3345
if (this.isValid([i, col])) {
34-
this.board[i][col] = 'Q'
35-
36-
if (this.solve(col + 1)) { return true }
37-
38-
// backtracking
39-
this.board[i][col] = '.'
46+
this.placeQueen(i, col)
47+
this.solve(col + 1)
48+
this.removeQueen(i, col)
4049
}
4150
}
4251

4352
return false
4453
}
4554

4655
printBoard () {
47-
// utility function to display the board
56+
console.log('\n')
4857
for (const row of this.board) {
4958
console.log(...row)
5059
}
5160
}
5261
}
5362

54-
function main () {
55-
const board = new NQueen(8)
56-
57-
board.printBoard()
58-
console.log('\n')
59-
60-
board.solve()
61-
62-
board.printBoard()
63-
}
64-
65-
main()
63+
export { NQueen }

Backtracking/tests/NQueen.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { NQueen } from '../NQueen'
2+
3+
describe('NQueen', () => {
4+
it('should return 2 solutions for 4x4 size board', () => {
5+
const _4Queen = new NQueen(4)
6+
_4Queen.solve()
7+
expect(_4Queen.solutionCount).toEqual(2)
8+
})
9+
10+
it('should return 92 solutions for 8x8 size board', () => {
11+
const _8Queen = new NQueen(8)
12+
_8Queen.solve()
13+
expect(_8Queen.solutionCount).toEqual(92)
14+
})
15+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy