def queene(n): helpQueene([-1]*n,0,n) def helpQueene(columnPositions,rowIndex,n): global count if rowIndex == n: count+=1 printSolution(columnPositions,n) return for column in range(n): columnPositions[rowIndex]=column if isValid(columnPositions,rowIndex): helpQueene(columnPositions,rowIndex+1,n) def isValid(columnPositions,rowIndex): for i in range(rowIndex): if columnPositions[i] == columnPositions[rowIndex]: return False elif abs(columnPositions[i]-columnPositions[rowIndex])==(rowIndex-i): return False return True def printSolution(columnPositions,n): for row in range(n): line="" for column in range(n): if columnPositions[row]==column: line+="Q " else: line+='_ ' print(line) print("\n") queene(8) print(count)
八皇后