八皇后问题---python

#-*-coding:utf-8-*-

count = 0
locs = []
def check_p(i,j):
    for x in range(len(locs)):
        if locs[x] == i:
            return False
        if abs(locs[x] - i) == abs(x - j):
            return False
    return True
def main(j):
    global count,locs
    for i in range(8):
        if check_p(i,j) == True:
            locs.append(i)
            if j == 7:
                count += 1
                print locs
                locs.pop()
                return
            main(j + 1)
            locs.pop()
if __name__ == "__main__":
    main(0)
    print count

主要思路就是递归和回溯

    原文作者:八皇后问题
    原文地址: https://www.cnblogs.com/lgy6534588/p/3447441.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞