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