Ejemplo n.º 1
0
        public Kruskal(WeightedEdgeGraph G)
        {
            queue = new Queue <WeightedEdge>();
            pq    = new MinPQ <WeightedEdge>(G.GetE());
            union = new int[G.GetV()];
            for (int x = 0; x < union.Count(); x++)//初始化连通分量
            {
                union[x] = x;
            }
            foreach (var e in G.edges())//初始化优先队列
            {
                pq.insert(e);
            }

            while (!pq.IsEmpty() && queue.Count < G.GetV() - 1)
            {
                var minE = pq.DeletePQHead();//最短边
                int v    = minE.either();
                int w    = minE.other(v);
                if (isConnect(v, w))
                {
                    continue;                 //会形成环
                }
                queue.Enqueue(minE);
                connect(v, w);//加入同一连通分量
            }
        }
Ejemplo n.º 2
0
        public Prim(WeightedEdgeGraph G)
        {
            dic    = new Dictionary <int, WeightedEdge>();
            marked = new bool[G.GetV()];
            queue  = new Queue <WeightedEdge>();

            visit(0, G);//从0节点开始
            while (dic.Count > 0)
            {
                int i = GetMinEdge();  //最短横切边的非树顶点
                queue.Enqueue(dic[i]); //最短横切边加入queue
                dic.Remove(i);
                visit(i, G);           //i被加入树,并且重新计算横切边情况
            }
        }