File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed
Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change 1+ class NQueen {
2+ constructor ( size ) {
3+ this . board = new Array ( size ) . fill ( '.' ) . map ( ( ) => new Array ( size ) . fill ( '.' ) )
4+ this . size = size
5+ }
6+
7+ isValid ( [ row , col ] ) {
8+ // function to check if the placement of the queen in the given location is valid
9+
10+ // checking the left of the current row
11+ for ( let i = 0 ; i < col ; i ++ ) {
12+ if ( this . board [ row ] [ i ] === 'Q' ) return false
13+ }
14+
15+ // checking the upper left diagonal
16+ for ( let i = row , j = col ; i >= 0 && j >= 0 ; i -- , j -- ) {
17+ if ( this . board [ i ] [ j ] === 'Q' ) return false
18+ }
19+
20+ // checking the lower left diagonal
21+ for ( let i = row , j = col ; j >= 0 && i < this . size ; i ++ , j -- ) {
22+ if ( this . board [ i ] [ j ] === 'Q' ) return false
23+ }
24+
25+ return true
26+ }
27+
28+ solve ( col = 0 ) {
29+ // function to solve the board
30+ if ( col >= this . size ) { return true }
31+
32+ for ( let i = 0 ; i < this . size ; i ++ ) {
33+ 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 ] = '.'
40+ }
41+ }
42+
43+ return false
44+ }
45+
46+ printBoard ( ) {
47+ // utility function to display the board
48+ for ( const row of this . board ) {
49+ console . log ( ...row )
50+ }
51+ }
52+ }
53+
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 ( )
You can’t perform that action at this time.
0 commit comments