1+ const displayBoard = ( board ) => {
2+ console . log ( "\n" ) ;
3+ for ( const row of board ) {
4+ console . log ( ...row )
5+ }
6+ }
7+
18class NQueen {
29 constructor ( size ) {
310 this . board = new Array ( size ) . fill ( '.' ) . map ( ( ) => new Array ( size ) . fill ( '.' ) )
411 this . size = size
12+ this . solutions = [ ]
513 }
614
715 isValid ( [ row , col ] ) {
@@ -25,41 +33,43 @@ class NQueen {
2533 return true
2634 }
2735
36+ placeQueen ( row , col ) {
37+ this . board [ row ] [ col ] = 'Q'
38+ }
39+
40+ removeQueen ( row , col ) {
41+ this . board [ row ] [ col ] = '.' ;
42+ }
43+
2844 solve ( col = 0 ) {
29- // function to solve the board
30- if ( col >= this . size ) { return true }
45+ if ( col >= this . size ) {
46+ this . solutions . push ( JSON . parse ( JSON . stringify ( this . board ) ) ) ;
47+ return true
48+ }
3149
3250 for ( let i = 0 ; i < this . size ; i ++ ) {
3351 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 ] = '.'
52+ this . placeQueen ( i , col )
53+ this . solve ( col + 1 )
54+ this . removeQueen ( i , col )
4055 }
4156 }
4257
4358 return false
4459 }
45-
46- printBoard ( ) {
47- // utility function to display the board
48- for ( const row of this . board ) {
49- console . log ( ...row )
50- }
51- }
5260}
5361
5462function main ( ) {
55- const board = new NQueen ( 8 )
56-
57- board . printBoard ( )
58- console . log ( '\n' )
59-
60- board . solve ( )
61-
62- board . printBoard ( )
63+ const nQueen = new NQueen ( 4 )
64+ displayBoard ( nQueen . board )
65+ nQueen . solve ( )
66+
67+ console . log ( "Number of solutions:" , nQueen . solutions . length ) ;
68+ nQueen . solutions . forEach ( ( solution ) => {
69+ displayBoard ( solution )
70+ } ) ;
6371}
6472
65- main ( )
73+ // main()
74+
75+ export { NQueen } ;
0 commit comments