1
+ /**
2
+ * @date 11/01/2018
3
+ * Method (Backtracking) taken from -- https://www.youtube.com/watch?v=0DeznFqrgAI
4
+ * Implemented in JavaScript by @MadhavBahlMD
5
+ */
6
+
7
+ function nqueens ( num ) {
8
+ console . log ( `Solving ${ num } Queens Problem` ) ;
9
+
10
+ // Initialize chessBoard
11
+ let chessBoard = [ ] ;
12
+ for ( let i = 0 ; i < num ; i ++ ) {
13
+ let thisRow = [ ] ;
14
+ for ( let j = 0 ; j < num ; j ++ )
15
+ thisRow . push ( 0 ) ;
16
+ chessBoard . push ( thisRow ) ;
17
+ }
18
+
19
+ // Check whether solution exists or not
20
+ if ( ! solveNqueens ( num , chessBoard , 0 ) ) {
21
+ console . log ( 'No combinations' ) ;
22
+ return 0 ;
23
+ }
24
+
25
+ printBoard ( chessBoard ) ;
26
+ return 1 ;
27
+ }
28
+
29
+ function solveNqueens ( num , chessBoard , col ) {
30
+ // If all queens are placed, return true
31
+ // We find all queens are place when the value of current column (col) becomes greater than or equals to N (num)
32
+ if ( col >= num )
33
+ return true ;
34
+
35
+ // Place all queen in all rows one by one and check whether they can be placed or not
36
+ for ( let i = 0 ; i < num ; i ++ ) {
37
+ // Check if the queen can be placed in ith row
38
+ if ( canBePlaced ( num , chessBoard , i , col ) ) {
39
+ chessBoard [ i ] [ col ] = 1 ;
40
+
41
+ // Use recursion to place rest of the queens
42
+ if ( solveNqueens ( num , chessBoard , col + 1 ) )
43
+ return true ;
44
+
45
+ // If current queen placement doesnt lead to a solution, remove the queen
46
+ chessBoard [ i ] [ col ] = 0 ;
47
+ }
48
+ }
49
+
50
+ return false ;
51
+ }
52
+
53
+ function canBePlaced ( num , chessBoard , row , col ) {
54
+ // Check row on left side
55
+ for ( let i = 0 ; i < col ; i ++ )
56
+ if ( chessBoard [ row ] [ i ] === 1 )
57
+ return false ;
58
+
59
+ // Check diagonals
60
+ for ( let i = row , j = col ; i >= 0 && j >= 0 ; i -- , j -- )
61
+ if ( chessBoard [ i ] [ j ] === 1 )
62
+ return false ;
63
+
64
+ for ( let i = row , j = col ; j >= 0 && i < num ; i ++ , j -- )
65
+ if ( chessBoard [ i ] [ j ] === 1 )
66
+ return false ;
67
+
68
+ // Return true
69
+ return true ;
70
+ }
71
+
72
+ function printBoard ( chessBoard ) {
73
+ let outputString ;
74
+
75
+ for ( let row of chessBoard ) {
76
+ outputString = '' ;
77
+ for ( let element of row )
78
+ outputString += element + ' ' ;
79
+ console . log ( outputString ) ;
80
+ }
81
+ }
82
+
83
+ nqueens ( 8 ) ;
0 commit comments