码迷,mamicode.com
首页 > 编程语言 > 详细

八皇后--python代码

时间:2016-09-06 21:15:43      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

迭代和递归方法的运用

import random
def prettyprint(solution):      #图形化处理数据
    def line(pos,length=len(solution)):   #单行数据的处理
        return .*(pos) + x+.*(length-pos-1)
    for pos in solution:       #画出每八行的图
        print line(pos)
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):
#    if len(state) == num-1:
#        for pos in range(num):
#            if not conflict(state,pos):
#                yield pos

def queens(num=8,state=()):
    for pos in range(num):
        print state
        if not conflict(state,pos):
            if len(state)==num-1:         #最后一个
                yield (pos,)              #迭代方法
            else:
                for result in queens(num,state+(pos,)):   #递归前七个数据
#                    print result
                    yield(pos,)+result

print bahuanghou
print list(queens(4))
#for i in list(queens(8)):
#    prettyprint(i)
#    print ‘next‘
#prettyprint(random.choice(list(queens(8))))

 

八皇后--python代码

标签:

原文地址:http://www.cnblogs.com/lcamry/p/5847068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!