2016-11-29 29 views
2

我在找到使用BFS的最短路徑,我很快得到這個RecursionError: maximum recursion depth exceeded in comparison,有關如何使用生成器來避免它的任何建議?或者使其迭代是唯一的好選擇?下面如何避免使用生成器的Python中的最大遞歸深度?

代碼:

def bfs_paths(graph, start, goal): 
    queue = [(start, [start])] 
    while queue: 
     (vertex, path) = queue.pop(0) 
     for next in graph[vertex] - set(path): 
      if next == goal: 
       yield path + [next] 
      else: 
       queue.append((next, path + [next])) 

def shortest_path(graph, start, goal): 
    try: 
     return next(bfs_paths(graph, start, goal)) 
    except StopIteration: 
     return None 

用例:

graph = {'A': set(['B', 'C']), 
     'B': set(['A', 'D', 'E']), 
     'C': set(['A', 'F']), 
     'D': set(['B']), 
     'E': set(['B', 'F']), 
     'F': set(['C', 'E'])} 

shortest_path(graph, 'A', 'F') # ['A', 'C', 'F'] 
+0

不,我正在談論使用生成器來處理它們。這是一個例子。我正在使用下一個發生器,但仍達到最大深度。 –

+0

如果您使用小圖(例如您的示例)得到此錯誤,那麼您有邏輯錯誤,而不是資源限制。除非該圖有超過一千個節點,否則不應該是一個問題。 –

+0

你的確切程序在我的機器上運行就好了 – Navidad20

回答

2

試試這個。它包括一個訪問集。我還修改了變量名'next'到'node',因爲它是內置函數。

def bfs_paths(graph, start, goal): 
    visited = set() 
    queue = [(start, [start])] 
    while queue: 
     vertex, path = queue.pop(0) 
     visited.add(vertex) 
     for node in graph[vertex]: 
      if node in visited: 
       continue 
      elif node == goal: 
       yield path + [node] 
      else: 
       queue.append((node, path + [node])) 

def shortest_path(graph, start, goal): 
    try: 
     return next(bfs_paths(graph, start, goal)) 
    except StopIteration: 
     return None 
+0

謝謝你的嘗試。但是,我仍然得到了達到最大遞歸深度的相同錯誤。 –

+0

如果您無法提供一些顯示您的錯誤的示例數據,我認爲這對幫助某人找到解決方案會有很長的路要走。 – Navidad20

+0

好吧,我正在建立一個github倉庫。給我5分鐘。 –

相關問題