Elegant Python-Eight queen problem simple solution

Source: Internet
Author: User

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

Related Article

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.