Skip to content

Commit 40f91ec

Browse files
authored
Added n-queen (TheAlgorithms#206)
1 parent 129ec51 commit 40f91ec

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

back-tracking/NQueen.js

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
class NQueen {
2+
constructor (size) {
3+
this.board = new Array(size).fill('.').map(() => new Array(size).fill('.'))
4+
this.size = size
5+
}
6+
7+
isValid ([row, col]) {
8+
// function to check if the placement of the queen in the given location is valid
9+
10+
// checking the left of the current row
11+
for (let i = 0; i < col; i++) {
12+
if (this.board[row][i] === 'Q') return false
13+
}
14+
15+
// checking the upper left diagonal
16+
for (let i = row, j = col; i >= 0 && j >= 0; i--, j--) {
17+
if (this.board[i][j] === 'Q') return false
18+
}
19+
20+
// checking the lower left diagonal
21+
for (let i = row, j = col; j >= 0 && i < this.size; i++, j--) {
22+
if (this.board[i][j] === 'Q') return false
23+
}
24+
25+
return true
26+
}
27+
28+
solve (col = 0) {
29+
// function to solve the board
30+
if (col >= this.size) { return true }
31+
32+
for (let i = 0; i < this.size; i++) {
33+
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] = '.'
40+
}
41+
}
42+
43+
return false
44+
}
45+
46+
printBoard () {
47+
// utility function to display the board
48+
for (const row of this.board) {
49+
console.log(...row)
50+
}
51+
}
52+
}
53+
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()

0 commit comments

Comments
 (0)