1
+ const displayBoard = ( board ) => {
2
+ console . log ( "\n" ) ;
3
+ for ( const row of board ) {
4
+ console . log ( ...row )
5
+ }
6
+ }
7
+
1
8
class NQueen {
2
9
constructor ( size ) {
3
10
this . board = new Array ( size ) . fill ( '.' ) . map ( ( ) => new Array ( size ) . fill ( '.' ) )
4
11
this . size = size
12
+ this . solutions = [ ]
5
13
}
6
14
7
15
isValid ( [ row , col ] ) {
@@ -25,41 +33,43 @@ class NQueen {
25
33
return true
26
34
}
27
35
36
+ placeQueen ( row , col ) {
37
+ this . board [ row ] [ col ] = 'Q'
38
+ }
39
+
40
+ removeQueen ( row , col ) {
41
+ this . board [ row ] [ col ] = '.' ;
42
+ }
43
+
28
44
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
+ }
31
49
32
50
for ( let i = 0 ; i < this . size ; i ++ ) {
33
51
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 )
40
55
}
41
56
}
42
57
43
58
return false
44
59
}
45
-
46
- printBoard ( ) {
47
- // utility function to display the board
48
- for ( const row of this . board ) {
49
- console . log ( ...row )
50
- }
51
- }
52
60
}
53
61
54
62
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
+ 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
+ } ) ;
63
71
}
64
72
65
- main ( )
73
+ // main()
74
+
75
+ export { NQueen } ;
0 commit comments