Python语言实现最短路径算法(Shortest Path)

 Python语言实现最短路径算法(Shortest Path)在Python中实现最短路径算法,可以使用Dijkstra算法。以下是一个使用Dijkstra算法来计算图中单源最短路径的示例:

import heapq

class Graph:
    def __init__(self, vertices):
        self.vertices = vertices
        self.adjacency_list = [[] for _ in range(vertices)]

    def add_edge(self, source, target, weight):
        self.adjacency_list[source].append((target, weight))
        self.adjacency_list[target].append((source, weight))  # 如果是有向图,则去掉这一行

    def dijkstra(self, start_vertex):
        distances = [float('inf')] * self.vertices
        distances[start_vertex] = 0
        visited = [False] * self.vertices
        pq = [(0, start_vertex)]

        while pq:
            current_distance, current_vertex = heapq.heappop(pq)

            if visited[current_vertex]:
                continue

            visited[current_vertex] = True

            for neighbor, weight in self.adjacency_list[current_vertex]:
                distance = current_distance + weight

                if distance < distances[neighbor]:
                    distances[neighbor] = distance
                    heapq.heappush(pq, (distance, neighbor))

        self.print_shortest_paths(start_vertex, distances)

    def print_shortest_paths(self, start_vertex, distances):
        print(f"Vertex\tDistance from Source {start_vertex}")
        for vertex, distance in enumerate(distances):
            print(f"{vertex}\t\t{distance}")

if __name__ == "__main__":
    graph = Graph(6)
    graph.add_edge(0, 1, 4)
    graph.add_edge(0, 2, 3)
    graph.add_edge(1, 2, 1)
    graph.add_edge(1, 3, 2)
    graph.add_edge(2, 3, 4)
    graph.add_edge(3, 4, 2)
    graph.add_edge(4, 5, 6)

    graph.dijkstra(0)

在这个示例中,我们创建了一个包含6个顶点的图,并添加了一些边。然后,我们从顶点0开始运行Dijkstra算法,计算并打印出从顶点0到所有其他顶点的最短路径距离。代码使用了Python的heapq模块来实现优先队列,以确保每次都选择距离最短的顶点进行处理。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值