【问题标题】:n queens program in python doesn't work [closed]python中的n皇后程序不起作用[关闭]
【发布时间】:2013-12-21 17:46:24
【问题描述】:

我在 n 个皇后的 python 中的程序有问题(在 nxn 板上放置 n 个皇后有多少种可能的方法)。似乎我的递归有问题,但我真的很无奈。有人能弄清楚出了什么问题吗?

def queens(N):

    ''' how many ways to place n queens on an NXN board? '''

    partial = []    # list representing partial placement of queens on the left columns
    return queens_rec(N,partial)

def queens_rec(N, partial):
    '''Given a partial solution to the n-Queens Problem ,
        return the number of options to place the rest of the queens.
        Recursively, in the end we will get the number of the options for
        the whole NxN board'''

    if len(partial)==N:
        return 1

    total = 0 #total of full solutions found
    row = 0

    while row<N:
        if isUnderAttack(partial,N,row)==False: #means it is not under Attack
            partial+=[row]

            total=total+queens_rec(N, partial)

            row+=1
            current = len(partial)

            partial = partial[0:current-1]

        else:
            row+=1

    return total

def isUnderAttack(partial, N, newRow):
    '''Checking if we can add a queen in row newRow, to the next column'''

    newCol = len(partial)

    for col in range(newCol): #not inculding newCol, checking all the previous columns
        oldRow = partial[col]


        #Checking horizontal attack from existing queen:
        if (newRow == oldRow):

            return True

        if (newCol - col == newRow - oldRow):

            return True

        if (newCol - col == oldRow - newRow):

            return True        

    return False

【问题讨论】:

  • 我总是得到 0 个解决方案
  • 你好 CnR,你能说得更具体点吗?你期待什么,你得到什么错误?您是否尝试过使用调试器单步执行您的代码?设置断点?添加日志以显示正在发生的事情?您得到 0 个解决方案,因为您还没有完成所有这些可以帮助您自己解决问题的基本事情......
  • 为什么如果 len(partial)==N 在queen_rec 中返回 1?
  • 我花了好几个小时试图找出问题所在,我确实放了打印命令来查看发生了什么,但为了方便起见,删除了它们。
  • @manu-fatto 因为如果我们在棋盘上安排了整个 n 个皇后,这意味着我们有一个解决方案

标签: python function recursion python-3.x n-queens


【解决方案1】:

你写道:

            partial+=[row]
            ...
            partial = partial[0:current-1]

第一个命令将列表部分修改到位。第二个制作副本,保持原始数组不变。

你应该写:

partial.append(row) # this is equivalent to:  partial += [row]
...
partial.pop() # modifes list in place

【讨论】:

  • 你帮了我很多,非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多