MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / NQueens

Class NQueens

Backtracking/NQueens.js:1–65  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class NQueens {
2 constructor(size) {
3 if (size < 0) {
4 throw RangeError('Invalid board size')
5 }
6 this.board = new Array(size).fill('.').map(() => new Array(size).fill('.'))
7 this.size = size
8 this.solutionCount = 0
9 }
10
11 isValid([row, col]) {
12 // function to check if the placement of the queen in the given location is valid
13
14 // checking the left of the current row
15 for (let i = 0; i < col; i++) {
16 if (this.board[row][i] === 'Q') return false
17 }
18
19 // checking the upper left diagonal
20 for (let i = row, j = col; i >= 0 && j >= 0; i--, j--) {
21 if (this.board[i][j] === 'Q') return false
22 }
23
24 // checking the lower left diagonal
25 for (let i = row, j = col; j >= 0 && i < this.size; i++, j--) {
26 if (this.board[i][j] === 'Q') return false
27 }
28
29 return true
30 }
31
32 placeQueen(row, col) {
33 this.board[row][col] = 'Q'
34 }
35
36 removeQueen(row, col) {
37 this.board[row][col] = '.'
38 }
39
40 solve(col = 0) {
41 if (col >= this.size) {
42 this.solutionCount++
43 return true
44 }
45
46 for (let i = 0; i < this.size; i++) {
47 if (this.isValid([i, col])) {
48 this.placeQueen(i, col)
49 this.solve(col + 1)
50 this.removeQueen(i, col)
51 }
52 }
53
54 return false
55 }
56
57 printBoard(output = (value) => console.log(value)) {
58 if (!output._isMockFunction) {
59 output('\n')
60 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected