回溯法解决八皇后问题(循环/递归)

# 回溯法解决八皇后问题


def place(l, k):
    for i in range(1,k):
        if l[i] == l[k] or abs(k-i) == abs(l[k]-l[i]):
            return False
    return True


# 循环
def queue(n):
    l = [0]*(n+1)
    k = 1
    while k >= 1:
        l[k] += 1
        while l[k] <= n and not place(l, k):
            l[k] += 1
        if l[k] <= n and k == n:
            print '-'*10
            for i in l:
                print i, " ",
            print
        # 进入下一个放置点
        elif l[k] <= n and k < n:
            k += 1
        # 回溯
        else:
            l[k] = 0
            k -= 1


# 递归
def queue2(n,k,l):
    if k == n+1:
        print '-' * 20
        for i in l:
            print i, " ",
        print
    else:
        for i in range(1,n+1):
            l[k] = i
            if place(l,k)and k<=8:
                queue2(n,k+1,l)

    原文作者:回溯法
    原文地址: https://blog.csdn.net/u011235518/article/details/52280479
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞