2013-07-21 50 views
0

我正在研究一個迷宮解決方案問題。代碼可以找到目標後,我不能讓Python打印出解決方案列表。但這是作業所必需的。如何讓我的迷宮功能打印出解決方案

有人可以幫我嗎?我剛學了3周的python。我想打印出python走向最終目標的每一步。這裏是我的代碼:

def mazeDetector(row,col): 
    c= m[row][col] 
    solution=[] 

    if c =="W": 
     print "Wall here: "+ str(row)+ ","+ str(col) 
     return False 
    elif c =="V": 
     print "Visited: " + str(row)+ ","+ str(col) 
     return False 
    elif c=="F": 
     print "Found: "+ str(row)+ ","+ str(col) 
     print solution 
     return True 

    print "visiting:"+ str(row)+ ","+ str(col) 
    solution.append((row,col),) 
    m[row][col]=="V" 
    if (col>0 and mazeDetector(row,col-1)): 
     return True 
    elif (row< len(m)-1 and mazeDetector(row+1,col)): 
     return True 
    elif (row>0 and mazeDetector(row-1, col)): 
     return True 
    elif (col<=len(m)-1 and mazeDetector(row, col+1)): 
     return True 
    return False 
mazeDetector(1,5) 

這裏是迷宮,W意味着牆壁,P意味着地方去,S手段開始,F意味着決賽:

[['W', 'P', 'P', 'W', 'W', 'W'], 
['W', 'W', 'P', 'W', 'P', 'S'], 
['W', 'W', 'P', 'W', 'P', 'W'], 
['P', 'P', 'P', 'P', 'P', 'W'], 
['F', 'W', 'P', 'W', 'W', 'W'], 
['W', 'P', 'P', 'P', 'P', 'W']] 

回答

1

,你必須解決方案傳遞到你的函數和每次不創建它:

def mazeDetector(row,col, solution): 
    c= m[row][col] 
    solution.append((row, col)) 
    if c =="W": 
     print "Wall here: "+ str(row)+ ","+ str(col) 
     return False 
    elif c =="V": 
     print "Visited: " + str(row)+ ","+ str(col) 
     return False 
    elif c=="F": 
     print "Found: "+ str(row)+ ","+ str(col) 
     print solution 
     return True 

    print "visiting:"+ str(row)+ ","+ str(col) 
    m[row][col]=="V" 
    if (col>0 and mazeDetector(row,col-1, list(solution))): 
     return True 
    elif (row< len(m)-1 and mazeDetector(row+1,col, list(solution))): 
     return True 
    elif (row>0 and mazeDetector(row-1, col, list(solution))): 
     return True 
    elif (col<=len(m)-1 and mazeDetector(row, col+1, list(solution))): 
     return True 
    return False 
mazeDetector(1,5, []) 

這裏的,如果它存在

def mazeDetector(row, col, solution): 
    solution.append((row, col)) 
    if m[row][col] == "F": return True, solution 
    m[row][col] = "V" 
    neighbors = [(row, col - 1), (row + 1, col), (row - 1, col), (row, col + 1)] 
    neighbors = filter(lambda (r, c): r >= 0 and c >= 0 and r < len(m) and c < len(m) and m[r][c] not in ("V", "W"), neighbors) 
    for r, c in neighbors: 
     t, sol = mazeDetector(r, c, list(solution)) 
     if t: return True, sol 
    return False, [] 

print mazeDetector(1, 5, [])[1] 
+0

謝謝sooo多!!! –

+0

呃我怎麼能讓mazeDectector返回解決方案? –

+0

您可以使用當前結果和解決方案的元組 –

0

你可以簡單地替換「P的在你實際解決的路線上用另一個符號可能'g'爲Go!

+0

怎麼可能我讓mazeDectector返回的解決方案,它返回路徑代碼? –

+0

返回找到並解決或調用的結果作爲tupple。 –