JAVA编程求单源最短路径_单源最短路径算法(BellmanFord算法)

///

/// 单源最短路径BellmanFord算法

///

public class BellmanFordAlg

{

///

/// 单源最短路径算法(BellmanFord算法)

///

/// 图

/// 原点

///

public bool DoBellmanFordAlg(Graphic g, Node s)

{

SingleSourcePath theSingleCalc = new SingleSourcePath();

theSingleCalc.InitializeGraphic(g, s);

for(int i=1;i

{

foreach (var theEdge in g.Edges)

{

theSingleCalc.Relax(theEdge);

}

}

foreach (var theEdge in g.Edges)

{

if (theEdge.Node2.TempVal > theEdge.Node1.TempVal + theEdge.Weight)

{

return false;

}

}

return true;

}

///

/// 贝尔曼福特算法,如果i,j不连接则权值为无穷大.

///

/// 图矩阵

/// 源点

/// 顶点数

///

public bool DoBellmanFordAlg(double[,] GraphicMatrix,int SourceNode,int n,double[] Distance,int[] Parents)

{

SingleSourcePath theSingleCalc = new SingleSourcePath();

double[] theDistance = Distance;

int[] theParents = Parents;

theSingleCalc.InitializeGraphic(theParents,theDistance,n,SourceNode);

for (int k = 0; k < n; k++)

{

for (int i = 0; i < n; i++)

{

for (int j = 0; j < n; j++)

{

if (i != j && double.IsInfinity(GraphicMatrix[i, j]) == false)

{

theSingleCalc.Relax(GraphicMatrix, theParents, theDistance, i, j);

}

}

}

}

for (int i = 0; i < n; i++)

{

for (int j = 0; j < n; j++)

{

if (i != j && double.IsInfinity(GraphicMatrix[i, j]) == false)

{

if (theDistance[j] > theDistance[i] + GraphicMatrix[i, j])

{

return false;

}

}

}

}

return true;

}

}

这个算法的要求比较低,不像 Dijkstra算法那样要求边权非负 ,也不要求无回路。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值