@@ -102,19 +102,50 @@ def is_valid(board):
102102 """ Returns True if there are no more than 1 "1" in any row, column, or diagonal;
103103 Else, it returns False. """
104104
105- return rows_valid (board ) and cols_valid (board ) and diags_valid (board )
105+ # We only have to check that the diagonals are valid, since the search
106+ # algorithm doesn't put more than 1 queen on a given row or column
107+ #return rows_valid(board) and cols_valid(board) and diags_valid(board)
108+ return diags_valid (board )
109+
110+
111+ def print_board_indented (board , row ):
112+ print ('\t ' * row + str (board ).replace ('\n ' , '\n ' + ('\t ' * row )))
113+
114+
115+ def search (board , row = 0 , cols_taken = ()):
116+ """ In-place search for solution to n-queens. """
117+
118+ # Return if we are at the maximum depth and the solution is valid
119+ if row == len (board ) and is_valid (board ):
120+ return True
121+
122+ # Otherwise, try each column and recursively work down the rows
123+ for col in range (len (board )):
124+ if col in cols_taken :
125+ continue
126+
127+ board [row ][col ] = 1
128+ print_board_indented (board , row )
129+
130+ if is_valid (board ):
131+ if search (board , row + 1 , cols_taken + (col ,)):
132+ return True
133+ else :
134+ board [row ][col ] = 0
135+ else :
136+ board [row ][col ] = 0
137+
138+ return False
106139
107140
108141def n_queens (size ):
109142 board = np .zeros ((size , size ))
110- for row in range (size ):
111- for col in range (size ):
112- board [row ][col ] = size * row + col
113- return board
143+ if search (board ):
144+ print ("Solution found:" )
145+ print (board )
146+ else :
147+ print ("No solution found" )
114148
115149if __name__ == '__main__' :
116150 board_size = 8
117- solution = n_queens (board_size )
118- print (solution )
119- print (diags_valid (solution ))
120-
151+ n_queens (board_size )
0 commit comments