N Queen in O ( n ) space | JavaScript program to for n Queen placement ; Function to check queens placement ; Helper Function to check if queen can be placed ; Function to display placed queen ; Driver code
function breakLine ( ) { document . write ( " " ) ; document . write ( " " ) ; document . write ( " " ) ; } let MAX = 10 ; let arr = [ ] ; let no = 0 ; function nQueens ( k , n ) { for ( let i = 1 ; i <= n ; i ++ ) { if ( canPlace ( k , i ) ) { arr [ k ] = i ; if ( k == n ) { display ( n ) ; } else { nQueens ( k + 1 , n ) ; } } } } function canPlace ( k , i ) { for ( let j = 1 ; j <= k - 1 ; j ++ ) { if ( arr [ j ] == i || ( Math . abs ( arr [ j ] - i ) == Math . abs ( j - k ) ) ) { return false ; } } return true ; } function display ( n ) { breakLine ( ) ; document . write ( " " + ++ no ) ; breakLine ( ) ; for ( let i = 1 ; i <= n ; i ++ ) { for ( let j = 1 ; j <= n ; j ++ ) { if ( arr [ i ] != j ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } document . write ( " " ) ; } breakLine ( ) ; } let n = 4 ; nQueens ( 1 , n ) ;