Нашли ошибку?

Быстрый маршрут курьера

ЛёгкаяНайти ошибку2 ошибкиГлава 7

#алгоритм Дейкстры#взвешенный графid: ga-fastest-route

Курьер ищет самый быстрый маршрут: graph[a][b] — минуты на дорогу из a в b. Функция fastest_route(graph, start, goal) реализует алгоритм Дейкстры в стиле книги: таблицы стоимостей и родителей, на каждом шаге обрабатывается самый дешёвый узел. Она возвращает (время, путь) или (math.inf, []). В функции две ошибки — найдите и исправьте их.

Пример

graph = {"склад": {"A": 5, "B": 2}, "B": {"A": 1, "клиент": 9}, "A": {"клиент": 3}}
fastest_route(graph, "склад", "клиент")   # (6, ["склад", "B", "A", "клиент"])

Решение

import math


def fastest_route(graph: dict[str, dict[str, int]], start: str, goal: str) -> tuple[float, list[str]]:
    """(минимальное время, путь) от start до goal или (math.inf, [])."""
    nodes = set(graph) | {n for edges in graph.values() for n in edges} | {start, goal}
    costs = {n: math.inf for n in nodes}
    parents: dict[str, str] = {}
    processed: set[str] = set()
    while True:
        node = min((n for n in nodes if n not in processed), key=lambda n: costs[n], default=None)
        if node is None or costs[node] == math.inf:
            break
        processed.add(node)
        for neighbor, minutes in graph.get(node, {}).items():
            new_cost = minutes
            if new_cost < costs[neighbor]:
                costs[neighbor] = new_cost
                parents[neighbor] = node
    if costs[goal] == math.inf:
        return math.inf, []
    path = [goal]
    while path[-1] != start:
        path.append(parents[path[-1]])
    return costs[goal], path[::-1]

Можно решать и в своём редакторе: «Скопировать с тестами» и запустите python3 fastest_route.py — тесты те же, результат покажет ✓ / ✗ и итог.