Queen eight, backtracking and Recursion

Source: Internet
Author: User

The eight-queen code of the python statement, from the basic Python tutorial, is short and can print 92 results at a time compared with other languages. At the same time, it can be extended to the ten queen problem after the nine emperors.

Problem: On an 8x8 board, each row is placed with a queen flag, and they do not conflict. Conflict definition: the same column cannot have two queens, and each diagonal line cannot have two queens. Of course, neither can the three queens, nor can the four be. I should be able to understand it with IQ.

  

Solution: backtracking and Recursion

 1 import random 2  3 def conflict(state,col): 4     row=len(state) 5     for i in range(row): 6         if abs(state[i]-col) in (0,row-i): 7             return True 8     return False 9 10 11     12 def queens(num=8,state=()):13     for pos in range(num):14         if not conflict(state, pos):15             if len(state)==num-1:16                 yield(pos,)17             else:18                 for result in queens(num, state+(pos,)):19                     yield (pos,)+result20 21 22 23 def queenprint(solution):24     def line(pos,length=len(solution)):25         return ‘. ‘*(pos)+‘X ‘+‘. ‘*(length-pos-1)26     for pos in solution:27         print line(pos)28         29 30 for solution in list(queens(8)):31     print solution32 print ‘  total number is ‘+str(len(list(queens())))33 print ‘  one of the range is:\n‘34 queenprint(random.choice(list(queens())))

 

Introduction:

1. Backtracking

2. Recursion

To be continued

 

Queen eight, backtracking and Recursion

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.