pqwsa 发表于 2017-4-28 10:40:44

Python 实现八皇后问题

  初学 Python , 写了一个八皇后的小程序,虽然算法效率不高,但这次是第一个用python实现

chess=[ for row in range(8)]
pos =0
i=0
flag =0
def check(i,pos):
if i==0:
return True
for counter in range(i):
if chess==1:
return False
for x in range(min(i,pos)):
if chess==1:
return False
if pos<7:
for y in range(min(i,7-pos)):
ifchess==1:
return False
return True
while i<8:
chess=1
if check(i,pos):
i=i+1
pos=0
else:
chess=0
while pos<7 and not check(i,pos):
pos=pos+1
if pos<=7 and check(i,pos):
chess=1
i=i+1
pos=0
else:
if (chess.index(1))<7:
pos = chess.index(1)+1
chess=0
i=i-1
else:
if i>=2:
pos =chess.index(1)+1
chess=0
chess=0
i=i-2
else:
break
if 1 in chess:
flag=flag+1
##      print "%d:Found:"%(flag)
##      
##      for k in range(len(chess)):
##            print chess
##      
##      print
##      print "*"*30
if (chess.index(1))<7:
pos = chess.index(1)+1
chess=0
i=7
else:
pos =chess.index(1)+1
chess=0
chess=0
i=6
print "there are %d solutions" %flag



  去掉程序中的注释,可以得到全部解:

******************************
90:Found:








******************************
91:Found:








******************************
92:Found:








******************************
there are 92 solutions
页: [1]
查看完整版本: Python 实现八皇后问题