Exemplo n.º 1
0
        /// <summary>
        /// 添加弧
        /// </summary>
        /// <param name="arcNode"></param>
        /// <param name="fromData"></param>
        /// <param name="toData"></param>
        /// <returns></returns>

        public bool addArcNode(ArcNode arcNode, object fromData, object toData)
        {
//			if(vertices.Contains(from)==false||vertices.Contains(to)==false)
//			{
//				//添加弧时要保证弧所连接的两个顶点要存在
//				return false;
//			}

            //添加弧时要保证弧所连接的两个顶点要存在


            VNode from = addVNode(fromData);

            VNode to = addVNode(toData);



            //保证从一个顶点到另一个顶点只有一条弧

            ArcNode arc = from.firstarc;

            for (; arc != null; arc = arc.nextarc)
            {
                if (arc.adjvex == to)
                {
                    return(false);                   //已经存在一条从顶点from到顶点to的弧
                }
            }

            //将弧添加到图中


            //如果这是从该顶点出发的第一条弧
            if (from.firstarc == null)
            {
                from.firstarc = from.endarc = arcNode;
            }
            else
            {
                //不是第一条弧
                from.endarc.nextarc = arcNode;
                from.endarc         = arcNode;
            }

            arcNode.adjvex = to;


            to.inDegree++;
            from.outDegree++;

            return(true);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 拓扑排序
        /// </summary>
        /// <returns>返回输出顶点数组</returns>
        public ArrayList topSort()
        {
            Stack stack = new Stack(startSize);

            ArrayList list = new ArrayList(startSize);

            // 将当前所有入度为零的顶点入栈

            for (int i = 0; i < vertices.Count; i++)
            {
                VNode node = (VNode)vertices[i];

                if (node.inDegree == 0)
                {
                    stack.Push(node);
                }
            }


            while (stack.Count != 0)
            {
                VNode v = (VNode)stack.Pop();
                // 输出无前驱的顶点
                list.Add(v.data);

                ArcNode arc = v.firstarc;

                //遍历依附于该顶点的所有弧
                for (; arc != null; arc = arc.nextarc)
                {
                    //所有邻接点的入度减1

                    arc.adjvex.inDegree--;
                    if (arc.adjvex.inDegree == 0)
                    {
                        //新的无前驱的顶点
                        stack.Push(arc.adjvex);
                    }
                }
            }
            return(list);
        }