Реализую алгоритм Дейкстры для такого графа. Ответ должен быть 8, у меня 9. Не пойму в чём ошибка
graph = {}
graph['s'] = {}
graph['s']['A'] = 5; graph['s']['B'] = 2
graph['A'] = {}
graph['A']['C'] = 4; graph['A']['D'] = 2
graph['B'] = {}
graph['B']['A'] = 8; graph['B']['D'] = 7
graph['C'] = {}
graph['C']['f'] = 3; graph['C']['D'] = 6
graph['D'] = {}
graph['D']['f'] = 1
graph['f'] = {}
costs = {}
costs['A'] = 5; costs['B'] = 2
costs['C'] = costs['D'] = costs['f'] = float('inf')
parents = {}
parents['A'] = parents['B'] = 's'
parents['C'] = parents['D'] = parents['f'] = None
processed = []
def find_lowest_cost_node(costs):
lowest_cost = float('inf')
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
node = find_lowest_cost_node(costs)
while node is not None:
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if costs[n] > new_cost:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
print(cost)
Ответы (1 шт):
Автор решения: MBo
→ Ссылка
Печатайте не стоимость пути к последнему обработанному узлу, а для конкретного узла
print(costs['f'])
