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

来源:互联网 发布:线性优化问题 编辑:程序博客网 时间:2024/05/16 04:37
/// <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算法那样要求边权非负 ,也不要求无回路。