graphx-最短路径

1.最近在总结图计算,把相关算法实现贴出来,坐下总结,作为督促。算法实现多数是graphx。

package org.apache.spark.graphx.algorithms

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.graphx.{EdgeDirection, VertexId, Graph}
import org.apache.spark.graphx.util.GraphGenerators


object Pregel_SSSP {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("lm-shotestpath").setMaster("local[*]")
    val sc = new SparkContext(conf)
    // A graph with edge attributes containing distances
    val graph: Graph[Long, Double] =
      GraphGenerators.logNormalGraph(sc, numVertices = 5).mapEdges(e => e.attr.toDouble)
    graph.vertices.foreach(println)
    graph.edges.foreach(println)
    val sourceId: VertexId = 0 // The ultimate source

    // Initialize the graph such that all vertices except the root have distance infinity.
    val initialGraph: Graph[(Double, List[VertexId]), Double] = graph.mapVertices((id, _) =>
      if (id == sourceId) (0
### 贝尔曼福特算法设计思路 贝尔曼福特(Bellman-Ford)算法用于解决单源最短路径问题,在加权图中找到从指定起点到其他各顶点之间的最短路径。该算法能够处理带有负权重边的情况,但不允许存在负权重环路[^1]。 #### 关键特性 - 支持负权重边 - 可检测并报告负权重环的存在 - 时间复杂度为 O(VE),其中 V 是节点数,E 是边的数量 ### 算法工作原理 通过逐步松弛操作来更新距离估计值直到收敛于实际最短路径长度。对于每一轮迭代: - 遍历所有的边 (u, v) 并尝试改进已知的最佳到达v的距离 d[v] - 如果发现更优路径,则更新d[v]=d[u]+w(u,v) 此过程重复执行V−1次(V表示顶点数量),因为任何简单路径最多包含|V|-1条边。 ### Python实现示例 ```python def bellman_ford(graph, source): # 初始化距离数组,默认无穷大;起始结点设为0 distance = {node: float('inf') for node in graph} predecessor = {node: None for node in graph} distance[source] = 0 # 进行 |V| - 1 次遍历 for _ in range(len(graph)-1): relaxed = False for u in graph: for v, weight in graph[u].items(): if distance[u] != float('inf') and distance[u] + weight < distance[v]: distance[v] = distance[u] + weight predecessor[v] = u relaxed = True if not relaxed: break # 检查是否存在负权重回路 for u in graph: for v, weight in graph[u].items(): if distance[u] != float('inf') and distance[u] + weight < distance[v]: raise ValueError("Graph contains a negative-weight cycle") return distance, predecessor ``` ### 图解说明 假设有一个简单的有向带权图 G=(V,E): ![bellman-ford](https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Bellman%E2%80%93Ford_algorithm.svg/800px-Bellman%E2%80%93Ford_algorithm.svg.png) 在这个例子中: - 初始状态下只有s->t被初始化成零。 - 经过第一次扫描后会得到新的临时最优解{s,t,x,y,z}={0,∞,-2,7,6}. - 接下来的几轮继续优化直至最终稳定下来获得全局最优解。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值