因此,我写了一种算法,可以找到无向,无权图中唯一不同的最短路径的数量。我相信这是正确的,而且我很难弄清运行时间是多少。非常感谢所有帮助!
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
答案 0 :(得分:1)
算法的运行时间是指数的。您可以通过不将顶点多次推入堆中,而应将计数器与每个顶点相关联,并在到达该顶点的每个新路径中递增计数器来避免这种情况。
尝试这样的事情:
initialize all counts of nodes to 0 // added
counts(v) = 1 // added
...
while Q is not empty
curr = pop(Q)
if( curr == end)
return counts(curr)
for all neighbors (nxt) of node curr do
if( level(nxt) == -1 )
level(nxt) = level(curr) + 1
counts(nxt) = counts(curr) // added
Push(Q, nxt)
else if( level(nxt) == level(curr) + 1 )
counts(nxt) += counts(curr) // added & removed
return 0
这与BFS-O(|E|+|V|)
具有相同的复杂性。