Python 中的自定义 Dijkstra 算法

Self-defined Dijkstra's algorithm in Python

我可以成功运行非函数格式的代码。但是,一旦我将所有内容打包成一个函数。我会收到一个错误。数据如下:

# A
graph_a = {}
graph_a['s'] = {}
graph_a['a'] = {}
graph_a['b'] = {}
graph_a['c'] = {}
graph_a['d'] = {}
graph_a['f'] = {}
graph_a['s']['a'] = 2
graph_a['s']['b'] = 5
graph_a['a']['b'] = 8
graph_a['a']['d'] = 7
graph_a['b']['d'] = 2
graph_a['b']['c'] = 4
graph_a['c']['d'] = 6
graph_a['c']['f'] = 3
graph_a['d']['f'] = 1

cost_a = {}
cost_a['a'] = 2
cost_a['b'] = 5
cost_a['f'] = float('inf')
cost_a['c'] = float('inf')
cost_a['d'] = float('inf')

parent_a = {}
parent_a['a'] = 's'
parent_a['b'] = 's'
parent_a['c'] = None
parent_a['d'] = None
parent_a['f'] = None

我还定义了最低成本节点函数,在每次迭代中找到成本最低的节点。

searched = []

def lowestcostnode(x):
    lowestnode = None
    lowestcost = float('inf')
    for node in x:
        if x[node] < lowestcost and node not in searched:
            lowestcost = x[node]
            lowestnode = node
    return lowestnode

我可以通过以下方式成功获取结果:

searched = []
node = lowestcostnode(cost_a)
while node is not None:
    currentcost = cost_a[node]
    neighbors = graph_a[node]
    for n in neighbors:
        if cost_a[n] > currentcost + neighbors[n]:
            cost_a[n] = currentcost + neighbors[n]
            parent_a[n] = node
    searched.append(node)
    node = lowestcostnode(cost_a)

结果如下:

cost_a
{'a': 2, 'b': 5, 'f': 8, 'c': 9, 'd': 7}

但是当我尝试将代码打包到一个函数中时,我收到了错误消息:

  1. 如果我在函数中创建搜索列表,该函数将生成如下错误消息:
def dijkstra(graph, parent, cost):
    searched = []
    node = lowestcostnode(cost)
    while node is not None:
        currentcost = cost[node]
        neighbors = graph[node]
        for n in neighbors:
            if cost[n] > currentcost + neighbors[n]:
                cost[n] = currentcost + neighbors[n]
                parent[n] = node
        searched.append(node)
        node = lowestcostnode(cost)
    print('parent as:', parent)
    print('cost as:', cost)
    return parent, cost

错误将是:

dijkstra(graph_a, cost_a, parent_a)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-57-00f1df255994> in <module>
----> 1 dijkstra(graph, parent, cost)

<ipython-input-56-517377fe9acb> in dijkstra(graph, parent, cost)
     12 def dijkstra(graph, parent, cost):
     13     searched = []
---> 14     node = lowestcostnode(cost)
     15     while node is not None:
     16         currentcost = cost[node]

<ipython-input-56-517377fe9acb> in lowestcostnode(x)
      5     lowestcost = float('inf')
      6     for node in x:
----> 7         if x[node] < lowestcost and node not in searched:
      8             lowestcost = x[node]
      9             lowestnode = node

NameError: name 'searched' is not defined

但是我在调​​用lowestcostnode函数之前已经定义了搜索的一行

预先感谢您的帮助。

您的来电: dijkstra(graph_a, cost_a, parent_a) 但根据您的函数定义,我希望: dijkstra(graph_a, parent_a, cost_a)

这能解决您的问题吗?