【发布时间】:2019-03-07 04:21:47
【问题描述】:
所以我编写了一个算法,可以在无向、未加权的图中找到不同最短路径的数量。我相信这是正确的,我无法弄清楚运行时间是多少。非常感谢所有帮助!
shortestPaths(undirected graph G, startNode v, endNode end)
initialize all levels of nodes to -1
count = 1;
initialize queue Q = {v}
level(v) = 0
while Q is not empty
curr = pop(Q)
if( curr == end)
w = pop(Q)
while(level(w)==level(curr))
if(w == end)
count++
w=pop(Q)
return count
for all neighbors (nxt) of node curr do
if( level(nxt) == -1 )
level(nxt) = level(curr) + 1
Push(Q, nxt)
else if( level(nxt) == level(curr) + 1 )
Push(Q, nxt)
else if( level(nxt) > level(curr) + 1)
Level(nxt) = Level(curr) + 1
return count
【问题讨论】:
-
当然是指数级的。至少 O(2^(|V|/2)),可能不会超过 O(2^|V|)。考虑到您可以在 O(|V|+|E|) 时间内完成此操作,这并不好。
-
我怎样才能达到 O(|V| + |E|)
-
我很困惑。无需尝试理解代码:开始和结束之间应该只有一条最短路径,对吧?那么不同的最短路径是什么?
-
因为可能有两条不同的相同长度的路径,它们都是最短的
标签: algorithm performance queue dijkstra breadth-first-search