代码改变世界

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

2012-08-01 21:13  java线程例子  阅读(488)  评论(0编辑  收藏  举报
/// <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算法那样要求边权非负 ,也不要求无回路。