This article mainly introduces python's method for solving the eight queens Problem Based on the right recursion. The example shows how to use the right recursion algorithm, for more information, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
All linear backtracking can be attributed to the form of right recursion, that is, a binary tree. Therefore, for a problem requiring only one solution, the program implemented by right recursion is much more elegant than the Backtracking Method.
Def Test (queen, n): '''. This is to Test the n (subscript, 0-7) is the row queen's location reasonable? ''' q = queen [n] for I in xrange (n ): if queen [I] = q or queen [I]-q = n-I or queen [I]-q = I-n: return False return Truedef Settle (queen, n): ''' this is responsible for placing the queen of line n (subscript, 0-7), each call, the queen will move at least one step '''queen [n] + = 1 while queen [n] <8 and not Test (queen, n ): queen [n] + = 1 return queen [n] <8def Solve (queen, n): ''' this resolves Nth (subscript, 0-7) row queen placement and subsequent placement of all queens ''' if n = 8: # after the placement of all queens, the output list print queen return True # if set to false, else: queen [n] =-1 # initialize the starting position of the queen of line n (start position-1, can be placed in 0-7) while Settle (queen, n): # if the queen is successfully placed if Solve (queen, n + 1): # if the other queen is placed, return True # if the resettlement is successful, return True return False # if the resettlement fails, returns false if _ name __= = '_ main _': Solve ([-1 for I in range (8)], 0) # The list value can be set at will, because it will be initialized # although we have not performed backtracking, in fact, every Solve function with the same parameters has tried multiple times # output: [0, 4, 7, 5, 2, 6, 1, 3] # It's much easier than backtracking.
I hope this article will help you with Python programming.