我有一个数据集,它是一个大型未加权循环图循环发生在大约 5-6 条路径的循环中。它由大约 8000 个节点组成,每个节点有 1-6 个(通常大约 4-5 个)连接。我正在做单对最短路径计算,并实现了以下代码来进行广度优先搜索。
from Queue import Queue
q = Queue()
parent = {}
fromNode = 'E1123'
toNode = 'A3455'
# path finding
q.put(fromNode)
parent[fromNode] = 'Root'
while not q.empty():
# get the next node and add its neighbours to queue
current = q.get()
for i in getNeighbours(current):
# note parent and only continue if not already visited
if i[0] not in parent:
parent[i[0]] = current
q.put(i[0])
# check if destination
if current == toNode:
print 'arrived at', toNode
break
上面的代码使用 Python 2.6 Queue 模块,getNeighbours() 只是一个子例程,它进行一次 MySQL 调用并将邻居作为元组列表返回,例如 (('foo',),('bar',))。SQL 调用很快。
代码工作正常,但是测试到大约 7 层的深度需要大约 20 秒才能运行(2.5GHz Intel 4GB RAM OS X 10.6)
我欢迎任何关于如何改进此代码的运行时间的评论。