Python 八皇后问题

2016/01/01 Python

使用 Python 解八皇后问题。

代码

# 判断是否冲突
def conflict(state, pos):
    if pos in state: return True
    nextY = len(state)
    for i in range(nextY):
        if nextY-pos == i-state[i] or nextY+pos == i+state[i]: return True

def queue(num, state=()):
    if num-1 == len(state):
        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 queue(num, state + (pos,)):
                    yield (pos,) + result

count = 0
for i in queue(8):
    count += 1
    print(i)

print(count)

Search

    Table of Contents