File tree Expand file tree Collapse file tree 2 files changed +34
-21
lines changed Expand file tree Collapse file tree 2 files changed +34
-21
lines changed Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ class NQueen {
2
2
constructor ( size ) {
3
3
this . board = new Array ( size ) . fill ( '.' ) . map ( ( ) => new Array ( size ) . fill ( '.' ) )
4
4
this . size = size
5
+ this . solutionCount = 0
5
6
}
6
7
7
8
isValid ( [ row , col ] ) {
@@ -25,41 +26,38 @@ class NQueen {
25
26
return true
26
27
}
27
28
29
+ placeQueen ( row , col ) {
30
+ this . board [ row ] [ col ] = 'Q'
31
+ }
32
+
33
+ removeQueen ( row , col ) {
34
+ this . board [ row ] [ col ] = '.'
35
+ }
36
+
28
37
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
+ }
31
43
32
44
for ( let i = 0 ; i < this . size ; i ++ ) {
33
45
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 )
40
49
}
41
50
}
42
51
43
52
return false
44
53
}
45
54
46
55
printBoard ( ) {
47
- // utility function to display the board
56
+ console . log ( '\n' )
48
57
for ( const row of this . board ) {
49
58
console . log ( ...row )
50
59
}
51
60
}
52
61
}
53
62
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 }
Original file line number Diff line number Diff line change
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
+ } )
You can’t perform that action at this time.
0 commit comments