八皇后问题Python解法




#八皇后问题

#!/usr/bin/env python
#coding:utf-8
# Author: wll
# Created Time: 2014年01月22日 星期三 22时50分36秒

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:
                               # len(state + 1)传给下一层
            for result in queens(num, state + (pos, )):
                yield  (pos,) + result



def printqueen(solution):
    def line (pos,length = len(solution)):
        return '.'*(pos) +'X' + '.'*(length -pos -1)
    for pos in solution:
        print line(pos)
    print '\n'
num = raw_input('Please input you quuen number :')
num = int(num)
#print list(queens(num))
results = list(queens(num))
for i in results:
    printqueen(i)


结果如下:

Please input you quuen number :4
.X..
...X
X...
..X.


..X.
X...
...X
.X..

Please input you quuen number :8
92

你可能感兴趣的:(递归,python,八皇后问题)