Пример #1
0
 //Searches through the parents of the passed UnionItems to determine which set it belongs to
 public UnionItem FindSet(UnionItem x)
 {
     if (x != x.parent)
     {
         x.parent = FindSet(x.parent);
     }
     return(x.parent);
 }
Пример #2
0
 //Sets the parent to link to UnionItems together
 public void Link(UnionItem x, UnionItem y)
 {
     if (x.rank > y.rank)
     {
         y.parent = x;
     }
     else
     {
         x.parent = y;
         if (x.rank == y.rank)
         {
             y.rank++;
         }
     }
 }
Пример #3
0
        //Kruskals algorithm, determines MST by stepping through edges by weight,
        //and adding them to the MST if doing so doesn't create a cycle,
        //which is determined by which set a vertex belongs to
        public void KruskalMST()
        {
            Edge[] MST              = new Edge[numVertices - 1];    //Creates an array to hold our MST, by def contains 1 less than total number of vertices
            Edge   nextEdge         = new Edge();                   //Container for our next edge variable
            int    currentEdgeCount = 0;                            //Current edge count
            int    currentEdgeIndex = 0;                            //The index of the current edge

            //Initialize MST array
            for (int i = 0; i < numVertices - 1; ++i)
            {
                MST[i] = new Edge();
            }

            //Sorts our edges using the native CompareTo method of Edge class
            Array.Sort(edges);

            //Steps through until MST is complete
            while (currentEdgeCount < numVertices - 1)
            {
                //Sets nextEdge to evaluate
                nextEdge = edges[currentEdgeIndex++];

                //Determines the set status of each end of the edge
                UnionItem x = FindSet(unionItems[nextEdge.source - 1]);
                UnionItem y = FindSet(unionItems[nextEdge.destination - 1]);

                //Check for cycle, by comparing parents of each node
                if (x != y)
                {
                    //If no cycle will be created, add the edge to the MST array, and union the two sets
                    MST[currentEdgeCount++] = nextEdge;
                    Union(x, y);
                }
            }
            //Sets our edges array to the newly created MST
            edges = MST;
        }
Пример #4
0
 //Unions two sets together
 public void Union(UnionItem x, UnionItem y)
 {
     Link(FindSet(x), FindSet(y));
 }
Пример #5
0
 //Makes a set containing only the passed UnionItem, setting the parent as itself
 public void MakeSet(UnionItem x)
 {
     x.parent = x;
     x.rank   = 0;
 }