Ideas:
- Use DFS.
- Coordinates are expressed in a one-dimensional array, where the subscript is a row and the element is a column. A[i]=j said to place the queen of line I on column J.
- Row by line (from top to bottom), decide which column to put (from left to right), so that you do not have to judge the row conflict, only need to judge the column conflict and the main slash backslash conflict.
- (Row-column) identifies a main slash, (row + column) identifies a slash.
The code below.
#coding =utf-8# style 1def Queen (A, cur=0): If Cur==len (a): print A else:for col in range (Len (a)): A[cur] = col #表示把第cur行的皇后放在col列上 ok = True for R in range (cur): if A[r]==col or R A[r]==cur-a[cur] or r+a[r]==cur+a[cur]: #判断是否跟前面的皇后冲突 OK = False if Ok:queen (A, cur+1) #风格2def Queen (A, cur=0): If Cur==len (a): print A else:for col in Ra Nge (Len (A)): a[cur] = col #表示把第cur行的皇后放在col列上 for R in range (cur): if A[r]==col or R A[r]==cur-a[cur] or r+a[r]==cur+a[cur]: #判断是否跟前面的皇后冲突 break Else:queen (A, cur +1) #风格3def Queen (A, cur=0): If Cur==len (a): print A else:for col in range (Len (a)): A[cur] = Col #表示把第cur行的皇后放在col列上 If all (A[r]!=a[cur] and r-a[r]!=cur-a[cur] and R+a[r]!=cur+a[cur] for R in range (cur) ): #判断是否跟前面的皇后冲突 Queen (A, cur+1) Queen ([None]*8)
The difference between the three styles is "
Judging whether it's a conflict with the Queen.Here.
OK flag---for...else-All (derivation).
What is good or bad?
Elegant Python-Eight queen problem simple solution