Printing all solutions in N | Java Program for above approach ; Program to solve N - Queens Problem ; All_rows_filled is a bit mask having all N bits set ; If rowmask will have all bits set , means queen has been placed successfully in all rows and board is displayed ; We extract a bit mask ( safe ) by rowmask , ldmask and rdmask . all set bits of ' safe ' indicates the safe column index for queen placement of this iteration for row index ( row ) . ; Extracts the right - most set bit ( safe column index ) where queen can be placed for this row ; these bit masks will keep updated in each iteration for next row ; Reset right - most set bit to 0 so , next iteration will continue by placing the queen at another safe column index of this row ; Backtracking , replace ' Q ' by ' ▁ ' ; Program to print board ; Driver Code ; Board size ; Function Call
import java . util . * ; public class NQueenSolution { static List < List < Integer > > result = new ArrayList < List < Integer > > ( ) ; public void solveBoard ( char [ ] [ ] board , int row , int rowmask , int ldmask , int rdmask ) { int n = board . length ; int all_rows_filled = ( 1 << n ) - 1 ; if ( rowmask == all_rows_filled ) { List < Integer > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( board [ i ] [ j ] == ' Q ' ) v . add ( j + 1 ) ; } } result . add ( v ) ; return ; } int safe = all_rows_filled & ( ~ ( rowmask ldmask rdmask ) ) ; while ( safe > 0 ) { int p = safe & ( - safe ) ; int col = ( int ) ( Math . log ( p ) / Math . log ( 2 ) ) ; board [ row ] [ col ] = ' Q ' ; solveBoard ( board , row + 1 , rowmask | p , ( ldmask p ) << 1 , ( rdmask p ) >> 1 ) ; safe = safe & ( safe - 1 ) ; board [ row ] [ col ] = ' ▁ ' ; } } public void printBoard ( char [ ] [ ] board ) { for ( int i = 0 ; i < board . length ; i ++ ) { System . out . print ( " ▁ " ) ; for ( int j = 0 ; j < board [ i ] . length ; j ++ ) { System . out . print ( board [ i ] [ j ] + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String args [ ] ) { int n = 4 ; char board [ ] [ ] = new char [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { board [ i ] [ j ] = ' ▁ ' ; } } int rowmask = 0 , ldmask = 0 , rdmask = 0 ; int row = 0 ; NQueenSolution solution = new NQueenSolution ( ) ; result . clear ( ) ; solution . solveBoard ( board , row , rowmask , ldmask , rdmask ) ; System . out . println ( result ) ; } }