Python learns the eight Queens question

Source: Internet
Author: User

1 ImportRandom2 #The conflict check, when defining state, uses state to flag each queen's position, where the index is used to denote the horizontal axis, and the base corresponding value represents the ordinate, for example: State[0]=3, which indicates that the Queen is on the 4th column of row 1th3 defconflict (state, NEXTX):4Nexty =Len (state)5      forIinchRange (nexty):6         #if the next queen's position is adjacent to the current Queen's position (both up and down, left and right) or on the same diagonal, then there is a conflict and needs to be rearranged7         ifABS (STATE[I]-NEXTX)inch(0, nexty-i):8             returnTrue9     returnFalseTen  One #The generator is used to generate the position of each queen, and the next Queen's position is realized by recursion.  A defQueens (num, state=()): -      forPosinchrange (num): -         if  notConflict (State, POS): the             #generate location information for the current queen -             ifLen (state) = = Num-1: -                 yield(POS,) -             #Otherwise, add the location information of the current queen to the status list and pass it on to the next queen.  +             Else: -                  forResultinchQueens (num, state+(POS,)): +                     yield(POS,) +result A  at  - #to visualize the chessboard, use X to indicate the position of each queen. - defPrettyprint (solution): -     defLine (POS, length=len (solution)): -         return '. '* (POS) +'X'+'. '* (length-pos-1) -      forPosinchSolution: in         PrintLine (POS) -  to if __name__=="__main__": +Prettyprint (Random.choice (List (Queens (8)))

Python learns the eight Queens question

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.