Beispiel #1
0
        public void ShortestPath(string start, Action <VertexNode, ArcNode> func = null)
        {
            Queue <VertexNode> queue = new Queue <VertexNode>();

            InitVisited();
            var vertexNode = Find(start);

            vertexNode.Visited = true;
            queue.Enqueue(vertexNode);
            while (queue.Count > 0)
            {
                VertexNode curruntNode = queue.Dequeue();
                ArcNode    arcNode     = curruntNode.FirstArc;
                //访问该顶点的所有邻接点
                while (arcNode != null)
                {
                    var nextVertex = arcNode.GetVertexNode();
                    func?.Invoke(curruntNode, arcNode);
                    if (!nextVertex.Visited)
                    {
                        queue.Enqueue(nextVertex);
                    }
                    nextVertex.Visited = true;
                    //访问下一个邻接点
                    arcNode = arcNode._nextArc;
                }
            }
        }
Beispiel #2
0
        //使用递归进行深度优先遍历
        public void DFS(VertexNode vrtexNode, Func <int, string, decimal, bool> func = null, int count = 0, decimal weight = 0)
        {
            vrtexNode.Visited = true;
            ArcNode node = vrtexNode.FirstArc;

            while (node != null)
            {
                count   = count == 0 ? 1 : count;
                weight += node._weight;
                //外置条件是否继续遍历
                var isdfs      = func?.Invoke(count, node.GetVertexNodeData(), weight) ?? false;
                var nextVertex = node.GetVertexNode();
                //如果邻接点未被访问,则递归访问它的边
                if (!nextVertex.Visited || isdfs)
                {
                    DFS(nextVertex, func, count + 1, weight);
                }
                weight -= node._weight;
                node    = node._nextArc;
            }
        }
Beispiel #3
0
 //添加有向边
 private void AddDirectedEdge(VertexNode fromVer, VertexNode toVer, decimal weight)
 {
     if (fromVer.FirstArc == null) //无邻接点时
     {
         fromVer.FirstArc = new ArcNode(toVer, weight);
     }
     else
     {
         ArcNode tmp, arcNode = fromVer.FirstArc;
         do
         {   //检查是否添加了重复边
             if (arcNode.GetVertexNodeData().Equals(toVer._data))
             {
                 throw new ArgumentException("添加了重复的边!");
             }
             tmp     = arcNode;
             arcNode = arcNode._nextArc;
         } while (arcNode != null);
         tmp._nextArc = new ArcNode(toVer, weight);
     }
 }