Python广度优先搜索优化

Oge*_*gen 6 python optimization dictionary

鉴于此代码......

import Queue

def breadthFirstSearch(graph, start, end):
    q = Queue.Queue()
    path = [start]
    q.put(path)
    while not q.empty():
        path = q.get()
        lastNode = path[len(path) - 1]
        if lastNode == end:
            return path
        for linkNode in graph[lastNode]:
            if linkNode not in path:
                newPath = []
                newPath = path + [linkNode]
                q.put(newPath)
Run Code Online (Sandbox Code Playgroud)

其中图是表示有向图的字典,例如{'stack':['overflow'], 'foo':['bar']},堆栈指向溢出而foo指向条.

这个广度优先搜索能够进一步优化吗?因为我打算在非常大的字典上使用它.

Nol*_*lty 10

为什么不保留一组访问过的节点,这样就不会一直打到相同的节点?这应该工作,因为它看起来不像你正在使用加权图.像这样的东西:

import Queue

def bfs(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])
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,我认为使用“collections.deque”会让它更快,因为“Queue.Queue”是高度同步的,在这种情况下这只是一个负担。请参阅 Keith Gaughan 的[此答案](http://stackoverflow.com/a/717261/517371)。 (2认同)