Python之八皇后问题

八皇后的问题解析请见:

点击打开链接

这里给出Python的解法,相对于C语言,Python比较简单,代码量较小,但是效率也只能呵呵了,貌似很难两全啊。

首先定义冲突函数:

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 queen(num = 8,state = ()):
    if len(state) == num-1:
        for pos in range(num):
            if not conflict(state,pos):
                yield (pos,)
    else:
        for pos in range(num):
            if not conflict(state,pos):
                for result in queen(num,state+(pos,)):
                    yield (pos,)+result

对输出进行形象化处理:

def prettyprint(solution):
    def line(pos,length = len(solution)):
        return '. '*pos + '* ' + '. '*(length - pos - 1)
    for pos in solution:
        print(line(pos))


你可能感兴趣的:(Python之八皇后问题)