python版本的N皇后算法

# /uer/bin/env python

# *_*coding=utf-8 *_*

x=[0 for i in range(1000)] #存放结果的列表

sum1=0

def Place(t):

global x

global n

for i in range(1,t):

if (abs(x[i]-x[t])==abs(i-t)) |(x[i]==x[t]):

return False

return True

def traceback(t):

global sum1

global x

global n

if(t>n):

sum1+=1

print(x[1:n+1])

else:

for i in range(1,n+1):

x[t] = i

if(Place(t)):

traceback(t+1)

return sum1

def main():

global n

n=int(input(“请输入皇后个数 “))

print(traceback(1))

if __name__ == ‘__main__’:

main()

点赞