Eight Queens question:
Put n Queens on the N*n board, down from the first line, each queen in one row, and each queen cannot be on the same column, diagonal, how many placement methods.
Ideas:
Typical backtracking questions:
1. When you want to place the last Empress, the default N-1 queen has all been placed, then verify that each position on the nth row is feasible, that is, whether it is in the same column or diagonal as the previous queen;
2. If you are not placing the last queen, backtrack. Back to the beginning of the first element, and then continue to return to the previous layer. Each layer thinks the next layer passes to itself the right information
1 def isconflict (state, NX):2 """3 Verify that the next queen to be placed is in conflict with the Queen.4 """5NY =Len (state)6 forIinchRange (NY):7 ifABS (STATE[I]-NX)inch(0, ny-i):8 returnTrue9 returnFalseTen One Adef Queens (num=8, state=[]): - """ - Main processing function the """ - forPinchrange (num): - ifNot isconflict (state, p): - ifLen (state) = = num-1: + yieldP - Else: + forResultinchQueens (num, state+[P]): A yield[result, p] at - - def play3 (l): - """ - to crack a sub-list in the returned results list - """ in Try: - Try: L +"' to except Typeerror:pass + Else: Raise TypeError - forIinchL: the forSinchPlay3 (i): * yields $ except TypeError:Panax Notoginseng yieldL - the def printqueens (l): + """ A Print Output Results the """ +L =play3 (L) -L =list (L) $n =Len (l) $ forIinchrange (n): - forJinchrange (n): - ifJ! =L[i]: thePrint'.', end=' ') - Else:WuyiPrint'Q', end=' ') thePrint' ') - Wu if__name__ = ='__main__': -L = List (Queens (5)) About print (L) $n =Len (l) -Print'there are {0} method of placement:'. Format (n)) - forIinchrange (n): -Print'--------------------') A Printqueens (L[i]) +Print'--------------------')
"Python" generator, backtracking and eight queens questions