2016-12-27 63 views
0

我嘗試了下面的代碼。如果有任何修改可以做出來,可以降低代碼的複雜性。我使用了名爲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我要去錯了???

感謝

+0

歡迎堆棧溢出。您似乎需要學習如何使用調試器逐行執行代碼,這可能使您可以輕鬆查明所遇問題的性質和位置。對於所有的意圖和目的,使用調試器都是任何程序員都需要的知識。有關更多信息,請參閱[如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –

回答

0

當您在initialize()初始化板你board['queen'][i]設置所有值-1。你的主程序調用if placequeen(0,board):這對於j每個值調用if free(i,j,board):,檢查board['queen'][i] == 0。最後一次檢查失敗,所有j,所以free()返回False,並且placequeen永遠不會添加一個女王,因此返回False,並且您的主程序甚至不會嘗試打印該板。

你的程序比需要的更復雜:我根本看不到你的字典,你可以將你的各種數組作爲單獨的變量。但是,您實際上並未要求簡化代碼。我不知道如何刪除這個非印刷錯誤,但考慮設置board['queen'][i]0而非-1

我同意@RandomDavis,你需要學習如何使用調試器。我用一個來找出你所說錯誤的原因,但其他人可能仍然存在。

+0

謝謝先生。我不得不改變免費(i,j,板)功能。我刪除了電路板['queen'] [i] == 0,然後輸出顯示在屏幕上。正如@RandomDavis所說,我確實遵循了這個代碼的調試策略。 –