Python 使用回溯和递归的N皇后问题中的错误

Python 使用回溯和递归的N皇后问题中的错误,python,recursion,backtracking,n-queens,Python,Recursion,Backtracking,N Queens,我首先实现了一个零矩阵,表示棋盘的所有位置最初都可用 n=int(input()) answer=[] restrictedIndices=[[0 for i in range(n)] for j in range(n)] dp(n,0,restrictedIndices,answer) 然后我实现了三个函数来填充受限的骰子 def columnFill(restrictedIndices,row,column,n): o=column restrictedIndices[ro

我首先实现了一个零矩阵,表示棋盘的所有位置最初都可用

n=int(input())
answer=[]
restrictedIndices=[[0 for i in range(n)] for j in range(n)]
dp(n,0,restrictedIndices,answer)
然后我实现了三个函数来填充受限的骰子

def columnFill(restrictedIndices,row,column,n):
    o=column
    restrictedIndices[row][o]=1
    while o+1<n:
        o+=1
        restrictedIndices[row][o]=1
    o=column
    while o-1>=0:
        o-=1
        restrictedIndices[row][o]=1    
    o=column
    return restrictedIndices


def rowFill(restrictedIndices,row,column,n):
    o=row
    restrictedIndices[o][column]=1
    while o+1<n:
        o+=1
        restrictedIndices[o][column]=1
    o=row
    while o-1>=0:
        o-=1
        restrictedIndices[o][column]=1
    o=row    
    return restrictedIndices


def diagonalFill(restrictedIndices,row,column,n):
    o=row
    p=column
    restrictedIndices[o][column]=1
    while o+1<n and p+1<n:
        o+=1
        p+=1
        restrictedIndices[o][p]=1
    o=row
    p=column
    while o-1>=0 and p+1<n:
        o-=1
        p+=1
        restrictedIndices[o][p]=1
    o=row
    p=column
    while o+1<n and p-1>=0:
        o+=1
        p-=1
        restrictedIndices[o][p]=1
    o=row
    p=column
    while o-1>=0 and p-1>=0:
        o-=1
        p-=1
        restrictedIndices[o][p]=1    
    o=row
    p=column
    return restrictedIndices
我得到了错误的输出,我想知道我们是否可以用这种方法解决这个问题,是否有更好的选择。
我希望我能理解递归和回溯是如何通过解决方案工作的,这将不起作用,因为存在以下问题:

  • answer
    从不填充:因此它只能是其初始值,即空列表
  • 虽然在找到解决方案时让
    dp
    返回-1,但调用者从不检查此值。因此,调用者并不知道它,而是转到其
    for
    循环的下一次迭代
  • dp
    的递归调用返回时,
    restrictedDices
    列表不会返回到其先前的状态。这意味着在
    for
    循环的下一次迭代中,条件
    [row][i]==1
    将始终为真——此单元格在第一次迭代中设置为1。您应该确保
    for
    循环的每次迭代都以完全相同的
    restrictedDices
    状态开始
我不会发布一个有效的解决方案,因为这在互联网上有大量的文档记录,Python的递归解决方案也可以在堆栈溢出上找到:

  • ,

非常感谢您,先生!
def dp(n,row,restrictedIndices,answer):
    print(restrictedIndices)
    if row==n:
        print("yes i got a solution")
        return -1
    print(restrictedIndices)
    for i in range(n):
        if restrictedIndices[row][i]==1:
            print("rejected",(row,i))
            continue
        
        else:
            x=[i for i in restrictedIndices]
            print(row,i)
            columnFill(restrictedIndices,row,i,n)
            rowFill(restrictedIndices,row,i,n)
            diagonalFill(restrictedIndices,row,i,n)
            dp(n,row+1,restrictedIndices,answer)