/// <summary> /// 單源最短路徑BellmanFord演算法 /// </summary> public class BellmanFordAlg { /// <summary> /// 單源最短路徑演算法(BellmanFord演算法) /// </summary> /// <param name="g">圖</param> /// <param name="s">原點</param> /// <returns></returns> public bool DoBellmanFordAlg(Graphic g, Node s) { SingleSourcePath theSingleCalc = new SingleSourcePath(); theSingleCalc.InitializeGraphic(g, s); for(int i=1;i<g.Nodes.Count()-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; } /// <summary> /// 貝爾曼福特演算法,如果i,j不串連則權值為無窮大. /// </summary> /// <param name="GraphicMatrix">圖矩陣</param> /// <param name="SourceNode">源點</param> /// <param name="n">頂點數</param> /// <returns></returns> 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演算法那樣要求邊權非負 ,也不要求無迴路。