2013-12-21 90 views
-4

我在我的程序中有n個皇后的python(有多少種可能的方法將n個皇后放在nxn板上)有問題。似乎我的遞歸有問題,但我真的很無奈。有人能夠弄清楚什麼是錯的嗎?在Python中的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

我總是得到0解決方案 – CnR

+0

你好CNR,可以請你更具體?你在期待什麼,你得到的錯誤是什麼?您是否嘗試過使用調試器逐步執行代碼?把斷點?添加日誌會顯示你正在發生什麼?你得到0解決方案,因爲你沒有做所有這些基本的事情,可以幫助你自己解決問題... –

+0

爲什麼在queen_rec你返回1如果len(partial)== N? –

回答

0

您寫道:

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

第一命令修改列表中的位置的部分。第二個創建一個副本並保持原始數組不變。

你應該寫:

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

你幫了我很多,非常感謝你。 – CnR