以下是一个使用Dijkstra算法实现最短路径的Python代码示例:

import heapq

def dijkstra(graph, start, end):
    """
    计算最短路径
    :param graph: 图形表示为字典
    :param start: 起始节点
    :param end: 目标节点
    :return: 最短路径
    """
    # 初始化距离字典和前置节点字典
    distances = {vertex: float('inf') for vertex in graph}
    distances[start] = 0
    previous_vertices = {vertex: None for vertex in graph}

    # 使用优先队列(堆)存储未处理的节点
    unvisited_vertices = [(0, start)]
    heapq.heapify(unvisited_vertices)

    # 遍历未处理的节点,直到找到目标节点
    while unvisited_vertices:
        current_distance, current_vertex = heapq.heappop(unvisited_vertices)

        # 如果当前节点已经被处理,则跳过
        if current_distance > distances[current_vertex]:
            continue

        # 如果找到目标节点,则返回路径
        if current_vertex == end:
            path = []
            while previous_vertices[current_vertex] is not None:
                path.append(current_vertex)
                current_vertex = previous_vertices[current_vertex]
            path.append(start)
            return path[::-1]

        # 处理当前节点的相邻节点
        for neighbor, weight in graph[current_vertex].items():
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                previous_vertices[neighbor] = current_vertex
                heapq.heappush(unvisited_vertices, (distance, neighbor))

    # 如果未找到目标节点,则返回None
    return None

该代码使用了一个字典来表示图,其中每个节点都是字典的一个键,它的值是一个字典,表示它的相邻节点和它们之间的距离。例如,下面的字典表示了一个简单的图:

graph = {
    'A': {'B': 1, 'C': 4},
    'B': {'A': 1, 'C': 2, 'D': 5},
    'C': {'A': 4, 'B': 2, 'D': 1},
    'D': {'B': 5, 'C': 1}
}

在这个图中,节点A有两个相邻节点B和C,与B相邻的节点是A、C和D,等等。

要使用该代码计算最短路径,只需调用dijkstra函数并传入图、起始节点和目标节点。例如,对于上面的图,要计算从节点A到节点D的最短路径,可以这样做:

path = dijkstra(graph, 'A', 'D')
print(path)  # 输出:['A', 'C', 'D']

这表示从A到D的最短路径是A->C->D,总长度为5

用python写一个路径规划的代码用于最短路径

原文地址: https://www.cveoy.top/t/topic/cluY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录