#-*-Coding=utf-8-*-"@Desc: Eight Queens algorithm, Python implementation @date:2017-10-13@author:henrywang ' import random# eight Queen's question previously not repeat the description # Verify that the new queen is in conflict with the previous Queen's location: In the same column or on the diagonal # state for the position tuple of the Queen that has been determined # NEXTX for the new Queen's position in the column def conflict (state, NEXTX): Nexty = Len (sta TE) # new Queen's line for I in range (len): # Against all previous Queens to Judge # State[i] The position of the column where the queen of line I is located # if State[i]-nextx = = 0, then the new queen and the Queen in the same column, return the comparison result to true # if ABS (State[i]-nextx) = = Nexty-i, then the new queen and the contrast queen on the diagonal, return the comparison result to True If ABS (STATE[I]-NEXTX) in (0, nexty-i): Return True # If the new queen and all the history queens are not on the same column or diagonal, return the comparison with false return False # Create Queen tuple, default queen tuple is empty def queens (num, state= ()): # for all the Queens on the line, judge each column position, 0-7 for POS in range (num): # Call Queen Location conflict authentication method If not conflict (state, POS): # If it is the last queen, yield this queen's position if Len (state) = = Num-1: Yield (POS,) Else: # If you can place the Queen in the current position, continue to find the next queen, until the position of all queens is found. For result In Queens (num, state+ (POS)): Yield (POS,) + result# Beautiful printing method def prettyprint (solution): Def line (POS, Length=len (solution)): # each row, the Queen's location prints X, other locations to print. Return '. ' * (POS) + ' X ' + '. ' * (length-pos-1) # for each Queen's line, print for POS in Solution:print (pos) if __name__ = = ' __main__ ': prin T (' A total of {} Possible Queen emission location selection '. Format (len (List (Queens (8)))) print (' One of the options is: ') prettyprint (Random.choice (List (Queens (8))) )
Python basic leak 7--eight Queen's question