📅  最后修改于: 2023-12-03 15:41:09.379000             🧑  作者: Mango
给定一个有向带权图和一个起点,找出起点到图中所有点的最短路径。如果存在负权边则无法使用Dijkstra算法,需要使用Bellman-Ford算法。
Dijkstra算法是基于贪心思想的单源最短路径算法,用于解决无负权边的问题,时间复杂度为O(nlogn)。该算法过程如下:
Bellman-Ford算法是基于动态规划的单源最短路径算法,可以解决带负权边的问题。该算法过程如下:
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
queue = [(0, start)]
while queue:
current_distance, current_node = heapq.heappop(queue)
if current_distance > distances[current_node]:
continue
for neighbor, weight in graph[current_node].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(queue, (distance, neighbor))
return distances
def bellman_ford(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
for i in range(len(graph) - 1):
for u in graph:
for v, weight in graph[u].items():
if distances[u] + weight < distances[v]:
distances[v] = distances[u] + weight
for u in graph:
for v, weight in graph[u].items():
if distances[u] + weight < distances[v]:
return None
return distances
Dijkstra算法适用于无负权边的情况,而Bellman-Ford算法可以处理带负权边的情况。在实际应用中,需要根据具体问题来选择合适的算法。