N Queen in O ( n ) space | C # 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
using System ; class GfG { static void breakLine ( ) { Console . Write ( " -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - " } static int = 10 ; static int [ ] arr = new int [ MAX ] ; static int no ; static 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 ) ; } } } } static bool canPlace ( int k , int i ) { for ( int j = 1 ; j <= k - 1 ; j ++ ) { if ( arr [ j ] == i || ( Math . Abs ( arr [ j ] - i ) == Math . Abs ( j - k ) ) ) { return false ; } } return true ; } static void display ( int n ) { breakLine ( ) ; Console . Write ( " Arrangement ▁ No . ▁ " + ++ no ) ; breakLine ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( arr [ i ] != j ) { Console . Write ( " TABSYMBOL _ " ) ; } else { Console . Write ( " TABSYMBOL Q " ) ; } } Console . WriteLine ( " " ) ; } breakLine ( ) ; } public static void Main ( String [ ] args ) { int n = 4 ; nQueens ( 1 , n ) ; } }