图的计算(2):带权图的最短路径

带权图(weighted digraph)

    设G=(V,E)是一简单图。称一元函数 w:E®R+ 为图G 的权函数,使得 对于每一条边eÎE均有一正实数w(e)ÎR+与之对应,称图G带有权w图,简称为带权图。记为G=(V,E, w)。

最短路(shortest path)

    设G=(V,E,w)是一带权图

    (1)设P=(ei1, ei2,¼, eik)G中的一条路。则路P的路长

定义为: w(P)=

 

 (2)从结点u到结点v的最短路P0满足下述条件的路:

             w(P0)=min{ w(P) ê

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一个比较复杂的问题,需要使用一些论算法。以下是一种基于Dijkstra算法的实现,可以求解起点和终点不确定的权图的最路径,你可以参考一下。 首先,我们需要定义一个的数据结构。可以使用邻接表来表示。 ```python class Graph: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) def add_edge(self, u, v, w): self.graph[u].append((v, w)) self.graph[v].append((u, w)) ``` 接下来,我们实现Dijkstra算法来求解最路径。 ```python import heapq def dijkstra(graph, source): distance = [float("inf")]*graph.V distance[source] = 0 heap = [(0, source)] while heap: (dist, current) = heapq.heappop(heap) if dist > distance[current]: continue for neighbor, weight in graph.graph[current]: w = weight + dist if w < distance[neighbor]: distance[neighbor] = w heapq.heappush(heap, (w, neighbor)) return distance ``` 最后,我们可以将这两个函数组合起来,来计算任意两个节点的最距离。以下是完整的代码。 ```python from collections import defaultdict import heapq class Graph: def __init__(self, vertices): self.V = vertices self.graph = defaultdict(list) def add_edge(self, u, v, w): self.graph[u].append((v, w)) self.graph[v].append((u, w)) def dijkstra(graph, source): distance = [float("inf")]*graph.V distance[source] = 0 heap = [(0, source)] while heap: (dist, current) = heapq.heappop(heap) if dist > distance[current]: continue for neighbor, weight in graph.graph[current]: w = weight + dist if w < distance[neighbor]: distance[neighbor] = w heapq.heappush(heap, (w, neighbor)) return distance def shortest_path(graph): result = [] for i in range(graph.V): dist = dijkstra(graph, i) result.append(dist) return result ``` 注意,这只是其中一种实现方式,并不是唯一的解决方案。你可以根据需求选择适合的算法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值