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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是实现A*算法最短路径算法Python代码示例: ```python import heapq def astar(start, goal, graph): """A* algorithm implementation""" # Initialize the open and closed lists open_list = [] closed_list = set() # Add the start node to the open list heapq.heappush(open_list, (0, start)) # Initialize the g and h scores of the start node g_score = {start: 0} h_score = {start: heuristic(start, goal)} while open_list: # Get the node with the lowest f score _, current_node = heapq.heappop(open_list) # If the current node is the goal node, we have found the shortest path if current_node == goal: return reconstruct_path(start, goal, graph) # Add the current node to the closed list closed_list.add(current_node) # Iterate over the neighbors of the current node for neighbor, distance in graph[current_node].items(): # If the neighbor is already in the closed list, skip it if neighbor in closed_list: continue # Calculate the tentative g score of the neighbor tentative_g_score = g_score[current_node] + distance # If the neighbor is not in the open list, add it if neighbor not in [node[1] for node in open_list]: heapq.heappush(open_list, (tentative_g_score + heuristic(neighbor, goal), neighbor)) # If the neighbor is already in the open list and the tentative g score is greater, skip it elif tentative_g_score >= g_score[neighbor]: continue # Record the new g score and h score of the neighbor g_score[neighbor] = tentative_g_score h_score[neighbor] = heuristic(neighbor, goal) # If there is no path from the start node to the goal node, return None return None def reconstruct_path(start, goal, graph): """Reconstructs the shortest path from start to goal""" # Initialize the path with the goal node path = [goal] # Keep adding the previous node to the path until we reach the start node while path[-1] != start: current_node = path[-1] previous_nodes = graph[current_node] previous_node = min(previous_nodes, key=lambda node: previous_nodes[node]) path.append(previous_node) # Reverse the path and return it return list(reversed(path)) def heuristic(node, goal): """Returns the estimated distance between node and goal""" # Use the Manhattan distance as the heuristic return abs(node[0] - goal[0]) + abs(node[1] - goal[1]) # Example usage: graph = { (0, 0): {(1, 0): 1, (0, 1): 1}, (1, 0): {(0, 0): 1, (1, 1): 1}, (0, 1): {(0, 0): 1, (1, 1): 1}, (1, 1): {(1, 0): 1, (0, 1): 1, (2, 1): 1}, (2, 1): {(1, 1): 1, (2, 2): 1}, (2, 2): {(2, 1): 1} } start = (0, 0) goal = (2, 2) print(astar(start, goal, graph)) # Output: [(0, 0), (1, 0), (1, 1), (2, 1), (2, 2)] ``` 该示例代码实现了A*算法,使用了堆(heapq)来优化寻找最小f值的节点。在计算路径时,使用了启发式函数(heuristic),这里使用的是曼哈顿距离(Manhattan distance)。该代码可以寻找从一个起始点到一个目标点的最短路径
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

亚丁号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值