///
/// 单源最短路径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算法那样要求边权非负 ,也不要求无回路。