【发布时间】:2020-09-20 07:49:14
【问题描述】:
众所周知,Dijkstra 会在给定图中找到从单个源节点到任何其他节点的最短路径。我尝试修改原始 Dijkstra 以找到一对源节点和目标节点之间的最短路径。只有在 Dijkstra 找到目标节点时才设置终止程序的终止条件似乎很容易。 但是,我在 Python 代码中设置的“终止条件”似乎导致了次优最短路径,而不是最优最短路径。 Dijkstra代码如下,
def dijkstra(adjList, source, sink):
#define variables
n = len(adjList) #intentionally 1 more than the number of vertices, keep the 0th entry free for convenience
visited = [False]*n
parent = [-1] *n
#distance = [float('inf')]*n
distance = [1e7]*n
heapNodes = [None]*n
heap = FibonacciHeap()
for i in range(1, n):
heapNodes[i] = heap.insert(1e7, i)
distance[source] = 0
heap.decrease_key(heapNodes[source], 0)
while heap.total_nodes:
current = heap.extract_min().value
#print("Current node is: ", current)
visited[current] = True
#early exit
if sink and current == sink:
break
for (neighbor, cost) in adjList[current]:
if not visited[neighbor]:
if distance[current] + cost < distance[neighbor]:
distance[neighbor] = distance[current] + cost
heap.decrease_key(heapNodes[neighbor], distance[neighbor])
if neighbor == sink and current != source: # this is a wrong logic , since the neighbor may not be selected as the next hop.
print("find the sink 1")
printSolution(source, sink, distance,parent)
break
if neighbor == sink:
print("find the sink2")
break
return distance
adjList = [
[],
[[2, 7], [3, 9], [6, 14]],
[[1, 7], [4, 15], [3, 10]],
[[1, 9], [2, 10], [4, 11], [6, 2]],
[[2, 15], [3, 11], [5, 6]],
[[4, 6], [6, 9]],
[[5, 9], [1, 14]]
]
dijkstra(adjList,1,4)
我想找到从节点1到节点4的路径,一共有三个路径:
path 1: 1 --> 2 --> 4 cost: 22
path 2: 1 --> 2 --> 3 --> 4 cost: 28
path 3: 1 --> 3 --> 4 cost: 20
path 4: 1 --> 3 --> 6 --> 5 --> 4 cost: 26
path 5: 1 --> 6 --> 3 --> 4 cost: 28
path 6: 1 --> 6 --> 5 --> 4 cost: 29
最初,Dijkstra 会选择路径 3:1 --> 3 --> 4,因为它的成本最低。
但是,我修改了终止条件,即当找到当前节点的邻接节点为目的地时,程序将结束。我得到了节点 1 和节点 4 之间路径的结果。结果是路径 1:1 --> 2 --> 4。 我分析了一下,这是因为我设置了错误的终止条件。当找到当前节点的邻接节点是目标时程序将终止,这是错误的,但我不知道在找到目标节点时设置适当的终止条件。请您提供一些想法吗?
【问题讨论】:
标签: algorithm shortest-path dijkstra