dijkstras算法找不到实际的最短路径

时间:2020-05-31 18:04:15

标签: python algorithm dijkstra

我正在尝试使用三个字典在python中实现dijkstras算法。但是,从Book到钢琴,我并没有真正走捷径。即使从节点PianoDrum set的父级之后,我的实现也不会更新它。

这是我的输出: parents-{'Poster': 'Book', 'Rare LP': 'Book', 'Piano': 'Bass guitar', 'Bass guitar': 'Rare LP', 'Drum set': 'Rare LP'} processed-['Poster', 'Rare LP', 'Bass guitar', 'Drum set', 'Piano'] costs-{'Poster': 0, 'Rare LP': 5, 'Bass guitar': 15, 'Drum set': 20, 'Piano': 20}

期望的结果- 父母-{'海报':'书', 'Rare LP':'Book', 'Piano':'Drum set', “低音吉他”:“ Rare LP”, 'Drum set':'Rare LP'} costs- {'海报':0,'稀有LP':5,'低音吉他':15,'鼓组':20,'钢琴':10}

这是我的实现方式

import math
# the graph
graph = {'Book':{'Poster':0, 'Rare LP':5}, 'Poster':{'Bass guitar':30, 'Drum set':35},
         'Rare LP':{'Bass guitar':15, 'Drum set':20}, 'Bass guitar':{'Piano':20},
         'Drum set':{'Piano':10},'Piano':{}}

# the costs table
costs = {'Poster':0, 'Rare LP':5, 'Bass guitar':math.inf, 'Drum set':math.inf, 'Piano':math.inf}

# the parents table
parents = {'Poster':'Book', 'Rare LP':'Book', 'Piano':''}


processed = []

def find_lowest_cost_node(costs):
    lowest_cost = math.inf
    lowest_cost_node = None
    # Go through each node.
    for node in costs:
        cost = costs[node]
        # If it's the lowest cost so far and hasn't been processed yet...
        if cost < lowest_cost and node not in processed:
            # ... set it as the new lowest-cost node.
            lowest_cost = cost
            lowest_cost_node = node
    return lowest_cost_node

# Run till all nodes are processed
while len(processed) < len(graph)-1:
    lowest_cost_node = find_lowest_cost_node(costs)

    #Loop through neighbours of the current lowest_cost_node
    for node in graph[lowest_cost_node].keys():


        if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
            costs[node] = graph[lowest_cost_node][node]
            parents[node] = lowest_cost_node
    processed.append(lowest_cost_node)

1 个答案:

答案 0 :(得分:0)

这部分看起来可疑:

if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
        costs[node] = graph[lowest_cost_node][node]

分配的成本不包括节点的原始成本。

尝试:

if costs[node] > costs[lowest_cost_node] + graph[lowest_cost_node][node]:
        costs[node] = costs[lowest_cost_node] + graph[lowest_cost_node][node]