列出 returns 空的 Nqueens 解决方案(写在 python 中)?

list returns empty for the Nqueens solution (written in python)?

我在网上看到一些 C++ 版本的 Nqueens 解决方案,并决定在 python 中对其进行编码,但由于某种原因,解决方案 列表 returns 是空的。

def is_safe(q , r):
    for i in range(q):
        tmp_q = position[i]
        if tmp_q == position[i] or tmp_q == r - (q - i) or tmp_q == r + (q - i):
            return False
    return True

def queensproblem(q):
    # q equals N, we have finished placed all the queens on each row
    if(q == N):
        solution = []
        for i in range(N):
            solution.append(position[i])
        solutions.append(solution)
    else:
        #look for all possibility in each row, 0...N
        for i in range(N):
            if(is_safe(q, i)):
                position[q] = i
                queensproblem(q + 1)

# q->number of queens placed
q = 0
N = 4
solutions = []
position = [None]*N
queensproblem(q)

print(solutions)

is_safe 中的逻辑错误:

    tmp_q = position[i]
    if tmp_q == position[i] or ...
        return False

此时,tmp_q 必须等于position[i] ...你只是强加了那个条件!如果 is_safe 进入这个循环,它将 return false。因此,您永远不会完成解决方案,并且列表仍然为空。

我不会修复你的整个程序......那不是 SO 的目的。然而,我会给你更多的帮助:这是我使用的代码,带有额外的语句来帮助调试。这就是我了解失败的 "texture" 的方式:is_safe returning False 以下任何内容第一任女王

print 是一个low-tech,有效的调试解决方案:当你有一个病态的程序时,问问哪里痛。 :-)

def is_safe(q , r):
    for i in range(q):
        tmp_q = position[i]
        if tmp_q == position[i] or tmp_q == r - (q - i) or tmp_q == r + (q - i):
            return False
    return True

def queensproblem(q):
    # q equals N, we have finished placed all the queens on each row
    if(q == N):
        solution = []
        for i in range(N):
            solution.append(position[i])
        solutions.append(solution)
        print "end of problem", solutions
    else:
        #look for all possibility in each row, 0...N
        for i in range(N):
            print "possibility loop", i, solutions, is_safe(q, i)
            if(is_safe(q, i)):
                position[q] = i
                print "recur", position, q+1
                queensproblem(q + 1)

# q->number of queens placed
q = 0
N = 4
solutions = []
position = [None]*N
queensproblem(q)

print(solutions)