Printing all solutions in N | Python 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 ; n = 4 board size ; Function Call
import math NEW_LINE result = [ ] NEW_LINE def solveBoard ( board , row , rowmask , ldmask , rdmask ) : NEW_LINE INDENT n = len ( board ) NEW_LINE all_rows_filled = ( 1 << n ) - 1 NEW_LINE if ( rowmask == all_rows_filled ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in board : NEW_LINE INDENT for j in range ( len ( i ) ) : NEW_LINE INDENT if i [ j ] == ' Q ' : NEW_LINE INDENT v . append ( j + 1 ) NEW_LINE DEDENT DEDENT DEDENT result . append ( v ) NEW_LINE DEDENT safe = all_rows_filled & ( ~ ( rowmask ldmask rdmask ) ) NEW_LINE while ( safe > 0 ) : NEW_LINE INDENT p = safe & ( - safe ) NEW_LINE col = ( int ) ( math . log ( p ) / math . log ( 2 ) ) NEW_LINE board [ row ] [ col ] = ' Q ' NEW_LINE solveBoard ( board , row + 1 , rowmask | p , ( ldmask p ) << 1 , ( rdmask p ) >> 1 ) NEW_LINE safe = safe & ( safe - 1 ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT board [ row ] [ col ] = ' ▁ ' NEW_LINE DEDENT def printBoard ( board ) : NEW_LINE INDENT for row in board : NEW_LINE INDENT print ( " | " + " | " . join ( row ) + " ▁ " ) NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT board = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT row = [ ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT row . append ( ' ▁ ' ) NEW_LINE DEDENT board . append ( row ) NEW_LINE DEDENT rowmask = 0 NEW_LINE ldmask = 0 NEW_LINE rdmask = 0 NEW_LINE row = 0 NEW_LINE result . clear ( ) NEW_LINE solveBoard ( board , row , rowmask , ldmask , rdmask ) NEW_LINE result . sort ( ) NEW_LINE print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT