使用Python解决N-queens(编码替代方案):

时间:2016-12-27 21:07:21

标签: python python-3.x

我尝试了以下代码。如果要进行任何修改,可以降低代码的复杂性。我使用了一个名为board的嵌套字典。

def initialize(board,n):
   for key in ['queen','row','col','nwtose','swtone']:
     board[key] = {}
   for i in range(n):
     board['queen'][i] = -1
     board['row'][i] = 0
     board['col'][i] = 0
   for i in range(-(n-1),n):
     board['nwtose'][i] = 0
   for i in range(2*n-1):
     board['swtone'][i] = 0

def printboard(board):
   for row in sorted(board['queen'].keys()):
     print((row,board['queen'][row]))

def free(i,j,board):
   return(board['queen'][i] == 0 and board['row'][i] == 0 and board['col'][j] == 0 and board['nwtose'][j-i] == 0 and board['swtone'][j+i] == 0)

def addqueen(i,j,board):
   board['queen'][i] = j
   board['row'][i] = 1 
   board['col'][j] = 1 
   board['nwtose'][j-i] = 1 
   board['swtone'][j+i] = 1 

def undoqueen(i,j,board):
   board['queen'][i] = -1
   board['row'][i] = 0 
   board['col'][j] = 0 
   board['nwtose'][j-i] = 0 
   board['swtone'][j+i] = 0


def placequeen(i,board):
   n = len(board['queen'].keys())
   for j in range(n):
        if free(i,j,board):
         addqueen(i,j,board)
         if i == n-1:
           return(True)
         else :
           extendsoln = placequeen(i+1,board)
         if extendsoln:
           return(True)
         else:
           undoqueen(i,j,board)
   else:
      return(False)


board = {}
n = int(input("How many Queens? "))
initialize(board,n)
if placequeen(0,board):
  printboard(board)

所以当我尝试这段代码时,我能够输入说4而不是输出。 我哪里出错了?

由于

1 个答案:

答案 0 :(得分:0)

initialize()初始化电路板时,您将所有值board['queen'][i]设置为-1。您的主程序会调用if placequeen(0,board):j调用if free(i,j,board):的每个board['queen'][i] == 0调用j。所有free()的最后一次检查都失败,因此False会返回placequeenFalse永远不会添加女王因此会返回board['queen'][i],而您的主程序甚至都没有尝试过打印电路板。

你的程序比需要的更复杂:我认为根本不需要你的字典,你可以将各种数组作为单独的变量。但是,您实际上并未要求简化代码。我不确定如何删除此非打印错误,但请考虑将0设置为-1而不是 #loader-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; } #loader { display: block; position: relative; left: 50%; top: 50%; width: 150px; height: 150px; margin: -75px 0 0 -75px; border-radius: 50%; border: 5px solid transparent; border-top-color: #aaa; border-right-color: #aaa; animation: spin 2s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

我同意@RandomDavis您需要学习如何使用调试器。我用一个来查找你陈述的bug的原因,但其他人可能仍然存在。