Classical backtracking algorithm: eight queens question
Algorithm requirements:
Place eight queens on the Chess Board (8*8) so that any two queens cannot be in the same row, in the same column, or on the same diagonal.
The chess chessboard is as follows:
Ask how many different ways there are, and point out the different kinds of methods.
#-*-coding:utf-8-*-__author__="Tyomcat"Print("****** Eight the solution to the Queen's problem ******")defNext_col (Current, n=8): Length=Len (current)ifLength = =N:returnDangerous= Current + [item forLinch[(Val + length-i, val-length + i) forI, ValinchEnumerate (current)] forIteminchLifItem >= 0 andItem <=N] forIinchrange (n):ifI not inchDangerous:yieldIdefQueens (N=8, columns=[]): ifLen (columns) = =N:yieldColumns forIinchnext_col (columns, N): appended= Columns +[i] forCinchQueens (n, appended):yieldCdefPrettyprint (solution):defLine (pos,lengh=len (solution)):return '.'* (POS) +'X'+'.'* (lengh-pos-1) forPosinchSolution:Print(Line (POS))if __name__=='__main__': I=0 forSolutioninchQueens (8): #print (I, solution)I+=1ifI > 1:Print('\ n') Print('Section'+ STR (i) +'Solution') Prettyprint (solution)
Python solves eight Queens problem