贪吃蛇食物最短路径

贪吃蛇食物最短路径

import heapq
from typing import List, Tuple


def shortest_food_path(foods: List[Tuple[int, int]], start: Tuple[int, int], end: Tuple[int, int]) -> int:
    def dijkstra(graph, start, end):
        heap = [(0, start)]
        visited = set()
        while heap:
            (distance, current) = heapq.heappop(heap)
            if current in visited:
                continue
            visited.add(current)
            if current == end:
                return distance
            for neighbor, weight in graph[current]:
                if neighbor not in visited:
                    heapq.heappush(heap, (distance + weight, neighbor))
        return -1

    graph = {}
    for i, food in enumerate(foods):
        graph[f'food_{i}'] = []
        for j, other_food in enumerate(foods):
            if i == j:
                continue
            weight = abs(food[0] - other_food[0]) + abs(food[1] - other_food[1])
            graph[f'food_{i}'].append((f'food_{j}', weight))

    start_food = f'start_food'
    graph[start_food] = []
    for i, food in enumerate(foods):
        weight = abs(start[0] - food[0]) + abs(start[1] - food[1])
        graph[start_food].append((f'food_{i}', weight))

    end_food = f'end_food'
    graph[end_food] = []
    for i, food in enumerate(foods):
        weight = abs(end[0] - food[0]) + abs(end[1] - food[1])
        graph[f'food_{i}'].append((end_food, weight))

    min_distance = 0
    for food in foods:
        distance = dijkstra(graph, start_food, f'food_{foods.index(food)}')
        if distance == -1:
            return -1
        min_distance += distance
        start_food = f'food_{foods.index(food)}'

    distance = dijkstra(graph, start_food, end_food)
    if distance == -1:
        return -1
    min_distance += distance
    return min_distance

你可能感兴趣的:(算法)