列表为Nqueens解决方案返回空(用python编写)?

时间:2016-01-27 20:29:36

标签: python recursion n-queens

我在网上看到了一些C ++版本的Nqueens解决方案,并决定用python编写代码,但由于某些原因,解决方案列表返回空。

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)

1 个答案:

答案 0 :(得分:2)

is_safe中的逻辑错误:

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

此时, tmp_q 必须等于位置[i] ...你刚才强迫这个条件!如果 is_safe 进入此循环,则返回false。因此,您永远不会完成解决方案,并且列表保持为空。

我不会修复你的整个程序......那不是那个SO的意思。但是,我会给你一些帮助:这是我使用它的代码,有额外的语句来帮助调试。这就是我学习失败的“纹理”的方法: is_safe 为第一位女王之下的任何东西返回 False

打印是一种低技术,有效的调试解决方案:当您有一个生病的程序时,请询问它在哪里受到伤害。 : - )

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)