Example #1
0
        public void GetShortestPath(string start, Action <string, string, decimal> func = null)
        {
            Station         vertexNode = Find(start);
            Queue <Station> queue      = new Queue <Station>();

            InitVisited();
            vertexNode.Visited = true;
            queue.Enqueue(vertexNode);

            while (queue.Count > 0)
            {
                Station curruntStation = queue.Dequeue();
                Route   route          = curruntStation.FirstRoute;
                //访问此顶点的所有邻接点
                while (route != null)
                {
                    var nextVertex = route.Station;
                    func?.Invoke(curruntStation.Name, route.GetDestinationStation(), route.Distance);
                    if (!nextVertex.Visited)
                    {
                        queue.Enqueue(nextVertex);
                    }
                    nextVertex.Visited = true;
                    //访问下一个邻接点
                    route = route.NextRoute;
                }
            }
        }
Example #2
0
 private static void VerifyRoute(Station endStation, Route route)
 {
     if (route.GetDestinationStation().Equals(endStation.Name))
     {
         throw new ArgumentException("添加了重复的边!");
     }
 }
Example #3
0
        //使用递归进行深度优先遍历
        private void DFS(Station startStation, Func <decimal, Stack <string>, bool> func = null, decimal weight = 0, Stack <string> stack = null)
        {
            startStation.Visited = true;
            Route route = startStation.FirstRoute;

            while (route != null)
            {
                weight += route.Distance;
                stack?.Push(route.GetDestinationStation());
                //外置条件是否继续遍历
                var isdfs      = func?.Invoke(weight, stack) ?? false;
                var nextVertex = route.Station;
                //如果邻接点未被访问,则递归访问它的边
                if (!nextVertex.Visited || isdfs)
                {
                    DFS(nextVertex, func, weight, stack);
                }
                stack.Pop();
                weight -= route.Distance;
                route   = route.NextRoute;
            }
        }