Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c423e6e

Browse files
Merge pull request TheAlgorithms#619 from mhihasan/update_nqeen_algo [TheAlgorithms#617]
Find all the solutions of NQueen
2 parents a9b1f89 + e9fd4a9 commit c423e6e

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)

AltStyle によって変換されたページ (->オリジナル) /