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模块来实现优先队列,以确保每次都选择距离最短的顶点进行处理。

在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模块来实现优先队列,以确保每次都选择距离最短的顶点进行处理。

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在