要查找图中的所有唯一路径并返回最便宜的路径,我们可以使用图论中的经典算法,如Dijkstra算法或A*算法。这里我们以Dijkstra算法为例,因为它适用于带权有向图,能够找到从起点到终点的最短路径(在这里假设“最便宜”指的是路径上的权重之和最小)。
以下是一个使用Dijkstra算法查找最便宜路径的简单示例:
import heapq
def dijkstra(graph, start, end):
queue = [(0, start, [])]
seen = set()
min_dist = defaultdict(int)
while queue:
(cost, node, path) = heapq.heappop(queue)
if node not in seen:
seen.add(node)
path = path + [node]
if node == end:
return cost, path
for c, neighbour in graph.get(node, []):
if neighbour not in seen:
old_cost = min_dist.get(neighbour, None)
new_cost = cost + c
if old_cost is None or new_cost < old_cost:
min_dist[neighbour] = new_cost
heapq.heappush(queue, (new_cost, neighbour, path))
return float("inf")
graph = {'A': [(2, 'B'), (3, 'C')],
'B': [(1, 'C'), (3, 'D')],
'C': [(2, 'D')],
'D': [(2, 'E')],
'E': []}
print(dijkstra(graph, 'A', 'D'))
通过上述方法和代码示例,你可以找到图中所有唯一路径中的最便宜路径。
领取专属 10元无门槛券
手把手带您无忧上云