图中节点之间的最短路径

时间:2018-04-23 18:32:37

标签: algorithm data-structures graph dijkstra

我不知道我是否应该在这里问这个问题,问题是算法。想象一下,你有一个无向图。边缘有不同的值。想象一下,有些顶点是好的"有些是"坏"。现在我想确定两个好的节点,以便它们之间的路径尽可能短(如果路径包含坏节点,那不是问题)。

2 个答案:

答案 0 :(得分:1)

你想要做的是立刻从所有好节点开始增长路径,然后在你发现两个相遇之后不久就停止。然后你找到了最短的路径。

有一个微妙的并发症。考虑一个三角形ABC。如果A-B和B-C的权重均为2,A-C为3,则在A-C之前查看边A-B和B-C。这意味着您在A-C(重量3)之前找到路径A-B-C(重量4)。但是在所有这些情况下,您会在找到第一个边缘之前看到边缘存在。

这是伪代码。

node_path_info is is a dictionary of vertex to information about the path
upcoming is priority queue of vertices to consider next, sorted on .cost

initialize node_path_info and upcoming
for node in list of good nodes:
    upcoming.add( {
        "node": node,
        "node_from": None,
        "cost": 0,
        "good_node", node,
    } )

best_path_cost = None
best_middle1 = None
best_middle2 = None
while upcoming:
    current = upcoming.pop()
    if current.node in good_node_from:
        if current.good_node == good_node_from[current.node]:
            pass # We found a loop
        else:
            cost = current.cost + node_path_info[current.node].cost
            if best_path_cost is None or cost < best_path_cost < best_path_cost:
                best_path_cost = cost
                best_middle1 = current.node
                best_middle1 = current.node_from
    else:
        node_path_info[current.node] = current
        if best_path_cost is not None: # still looking for first path
            for (next_node, weight) in get_connected_weight(current.node):
                upcoming.add({
                    "node": next_node,
                    "node_from": current.node,
                    "cost": current.cost + weight,
                    "good_node", current.good_node,
                })

path1 = path from best_middle1 back
path2 = path from best_middle2 back
path1 + reversed(path2) is your answer.

在最坏的情况下,您需要两次访问所有边缘。使用随机连接图和2个良好节点,您将访问连接到O(sqrt(n))个顶点的所有边。

答案 1 :(得分:0)

一种方法是添加一个源节点,该节点具有定向连接(权重为0)到每个良好节点。

然后运行Dijkstra算法以找到从源节点到每个其他节点的最短路径。

在运行Dijkstra算法时,还要跟踪哪个好节点最接近。

然后在边A-> B上进行最后一次通过以找到最便宜的值“距离A的良好节点的距离”+“边缘的重量”+“距离B的良好节点的距离”,仅包括边缘与A最接近的良好节点不等于与B最接近的良好节点。

相关问题