N Queen in O ( n ) space | CPP code 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
#include <bits/stdc++.h> NEW_LINE #define breakLine  cout << " NEW_LINE -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - " #define MAX 10 using namespace std ; int arr [ MAX ] , no ; void nQueens ( int k , int n ) ; bool canPlace ( int k , int i ) ; void display ( int n ) ; void nQueens ( int k , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { if ( canPlace ( k , i ) ) { arr [ k ] = i ; if ( k == n ) display ( n ) ; else nQueens ( k + 1 , n ) ; } } } bool canPlace ( int k , int i ) { for ( int j = 1 ; j <= k - 1 ; j ++ ) { if ( arr [ j ] == i || ( abs ( arr [ j ] - i ) == abs ( j - k ) ) ) return false ; } return true ; } void display ( int n ) { breakLine cout < < " Arrangement ▁ No . ▁ " << ++ no ; breakLine for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( arr [ i ] != j ) cout << " TABSYMBOL _ " ; else cout << " TABSYMBOL Q " ; } cout << endl ; } breakLine } int main ( ) { int n = 4 ; nQueens ( 1 , n ) ; return 0 ; }