Python implements the eight-Queen Problem Based on the tracing algorithm subset tree template, and the python queen
The example in this article describes how Python implements the 8 Queen's problem based on the subset tree template of the Backtracking Method. We will share this with you for your reference. The details are as follows:
Problem
Eight queens are placed on 8x8 garbled chess so that they cannot attack each other. That is, neither of them can be in the same row, column, or diagonal line, how many methods are available.
Analysis
In order to simplify the problem, considering the different rows of the eight queens, one queen is placed in each row, and the queens in each row can be placed in 0th, 1, 2 ,..., 7 columns, we think each row of the Queen has eight States. Then, we only need to apply the subset tree template, starting from 0th rows, from top to bottom, to traverse the eight States of each row.
Code:
'''Eight queens question ''' n = 8 x = [] # A solution (n element array) X = [] # A group of solutions # Conflict Detection: determine whether x [k] matches the first x [0 ~ K-1] conflict def conflict (k): global x for I in range (k): # traverse before x [0 ~ K-1] if x [I] = x [k] or abs (x [I]-x [k]) = abs (I-k ): # determine whether it conflicts with x [k] return True return False # apply the subset tree template def queens (k): # Reach global n, x, X if k> = n: # exceeds the bottommost line # print (x) X. append (x [:]) # Save (a solution). Note that x [:] else: for I in range (n): # traverse 0th ~ N-1 column (n States) x. append (I) # Place the Queen in column I and stack it if not conflict (k): # pruning queens (k + 1) x. pop () # trace back, stack # visualize the solution (based on a solution x, restore the board. 'X' indicates Queen) def show (X): global n for I in range (n): print ('. '* (x [I]) + 'X' + '. '* (n-x [I]-1) # test queens (0) # print (X [-1],' \ n') from row 0th ') show (X [-1])