代码改变世界

单源最短路径算法(有向无回路)

2012-08-01 21:18  java线程例子  阅读(313)  评论(0编辑  收藏  举报

 /// <summary>
    /// 有向无回路图中的单源最短路径算法
    /// </summary>
    public class DAG_Shortest_Paths
    {
        /// <summary>
        /// 有向无回路图中的单源最短路径
        /// </summary>
        /// <param name="g">有向无回路图</param>
        /// <param name="s">源点s</param>
        public void DAGShortestPaths(Graphic g, Node s)
        {
            GraphicSearchAlg theGS = new GraphicSearchAlg();
            //获取拓扑排序
            var theNodes = theGS.TopoLogicalSort(g);
            SingleSourcePath theSSP = new SingleSourcePath();
            //初始化图
            theSSP.InitializeGraphic(g, s);
            foreach (Node theNode in theNodes)
            {
                foreach (var theAdjNode in theNode.AdjNodes)
                {
                    //利用松弛技术.
                    theSSP.Relax(theAdjNode.Value);
                }
            }
        }
    }

在图的算法中,邻接表表示确实可以改善时间复杂度,但邻接矩阵表示却有利于规模计算。两者如何选择,需根据实际情况来选择,后面的最大流等算法中,可以两者结合来发挥各自的优势。