八皇后 用Python写的源码 谢谢
1个回答
展开全部
import random
'''
设两个不同的皇后分别在j,k行上,x[j],x[k]分别表示在j,k行的那一列上。
那么不在同一对角线的条件可以写为abs((j-k))!=abs(x[j]-x[k])
'''
def conflict(state,nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i]-nextX) in (0,nextY - i):
return True
return False
def queens(num,state=()):
for pos in range(num):
if not conflict(state,pos):
if len(state) == num - 1:
yield (pos,)
else:
for result in queens(num,state + (pos,)):
yield (pos,)+result
def prettyprint(solution):
def line(pos,length=len(solution)):
return '.' * (pos) + 'X' + '.'*(length-pos-1)
for pos in solution:
print line(pos)
if __name__=="__main__":
prettyprint(random.choice(list(queens(8))))
'''
设两个不同的皇后分别在j,k行上,x[j],x[k]分别表示在j,k行的那一列上。
那么不在同一对角线的条件可以写为abs((j-k))!=abs(x[j]-x[k])
'''
def conflict(state,nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i]-nextX) in (0,nextY - i):
return True
return False
def queens(num,state=()):
for pos in range(num):
if not conflict(state,pos):
if len(state) == num - 1:
yield (pos,)
else:
for result in queens(num,state + (pos,)):
yield (pos,)+result
def prettyprint(solution):
def line(pos,length=len(solution)):
return '.' * (pos) + 'X' + '.'*(length-pos-1)
for pos in solution:
print line(pos)
if __name__=="__main__":
prettyprint(random.choice(list(queens(8))))
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询