Dijkstras Algotithm - 到特定节点的距离

时间:2018-04-01 09:53:02

标签: python function dijkstra

我有工作代码可以找到从我的起始节点到所有其他节点的距离,产生以下结果: {'0':0,'1':2,'2':5,'3':9} 我需要的是一个函数,它允许我输入我的一个节点并返回第一个函数给出的距离,例如输入'3'将输出9.我该怎么做?

import heapq

graph = {
    '0': {'1': 2, '2': 5},
    '1': {'2': 3},
    '2': {'3': 4},
    '3': {'0': 21, '1': 8},
}


def di(graph, source):
    priority_queue = []
    heapq.heappush(priority_queue, (0, source))
    visited = {}
    while priority_queue:
        (current_distance, current) = heapq.heappop(priority_queue)

        visited[current] = current_distance

        if current not in graph: continue
        for neighbour, distance in graph[current].items():

            if neighbour in visited: continue

            new_distance = current_distance + distance
            heapq.heappush(priority_queue, (new_distance, neighbour))

return visited

1 个答案:

答案 0 :(得分:0)

尝试拆分此节点点数组,然后只访问最后一个(或感兴趣的点)。如果没有其他条件适用,您可以尝试使用正则表达式拆分字符串本身并使用拆分字符“,”。这将为您提供一系列字符串,您可以通过索引访问这些字符串。 java代码中的示例:

import textract
def convert_to_txt(filename):
    try:
        my_text = textract.process(filename, encoding='ascii')
    except Exception as e:
        msg = "Couldn't able to open the file: {}".format(filename)
        raise RuntimeError(msg)
    return my_text

输出将为'3':9,您可以进一步处理(转换,计算,等等)。