示例#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;
                }
            }
        }
示例#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;
            }
        }