Python广度优先搜索优化

时间:2013-05-25 06:38:09

标签: 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)

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

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

1 个答案:

答案 0 :(得分: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])