Elegant python and elegant python
Ideas:
- Use DFS.
- Use A one-dimensional array to express coordinates. The subscript is A row, and the element is column. A [I] = j indicates placing the queen of row I on column j.
- A row traverses (from top to bottom) in sequence to determine the column to be placed (from left to right). In this way, you do not need to determine the row conflict, but you only need to determine the column conflict and the primary slash subslash conflict.
- (Row-column) identifies the primary slash, (row + column) identifies the secondary 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 [cur] = col # indicates placing the queen of the cur row on the col column 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]: # determine whether there is A conflict with the queen. OK = False break if OK: queen (A, cur + 1) # style 2def queen (A, cur = 0 ): if cur = len (A): print A else: for col in range (len ()): A [cur] = col # indicates placing the queen of the cur row on the col column for r in range (cur): If A [r] = col or r-A [r] = cur-A [cur] or r + A [r] = cur + A [cur]: # determine if there is A conflict with the queen break else: queen (A, cur + 1) # style 3def queen (A, cur = 0): if cur = len (): print A else: for col in range (len (A): A [cur] = col # indicates placing the queen of the cur row on the col column 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): # determine whether the queen is in conflict with the queen (A, cur + 1) queen ([None] * 8)
The differences between the three styles are"
Determine whether there is a conflict with the Queen"Here.
They are OK flag-> for... else...-> all (derivation ).
Which is better or worse?