鉴于此代码...
import Queue
def breadthFirstSearch(graph, start, end):
q = Queue.Queue()
path = [start]
q.put(path)
visited = set([start])
while not q.empty():
path = q.get()
last_node = path[-1]
if last_node == end:
return path
for node in graph[last_node]:
if node not in visited:
visited.add(node)
q.put(path + [node])
其中graph 是表示有向图的字典,例如{'stack':['overflow'], 'foo':['bar']} 即stack 指向overflow 而foo 指向bar。
为什么当我用集合中的 deque 替换 Queue.Queue 以提高效率时,我没有得到相同的结果?
from collections import deque
def breadthFirstSearch(graph, start, end):
q = deque()
path = [start]
q.append(path)
visited = set([start])
while q:
path = q.pop()
last_node = path[-1]
if last_node == end:
return path
for node in graph[last_node]:
if node not in visited:
visited.add(node)
q.append(path + [node])