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 {
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 }
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