Elegant python and elegant python

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.