我嘗試了下面的代碼。如果有任何修改可以做出來,可以降低代碼的複雜性。我使用了名爲board的嵌套字典。使用Python解決N皇后問題(編碼方案):
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,但沒有得到輸出。 凡excatly我要去錯了???
感謝
歡迎堆棧溢出。您似乎需要學習如何使用調試器逐行執行代碼,這可能使您可以輕鬆查明所遇問題的性質和位置。對於所有的意圖和目的,使用調試器都是任何程序員都需要的知識。有關更多信息,請參閱[如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –