Ejemplo n.º 1
0
        /// <summary>
        /// Method that computes number of components in a graph and assigns
        /// component number to every vertex.
        /// </summary>
        public void GetNumberOfComponents()
        {
            UFvertex []   uf    = new UFvertex[graph.Count];
            HashSet <int> comps = new HashSet <int>();

            int [] components = new int[graph.Count];
            for (int i = 0; i < graph.Count; i++)
            {
                uf[i] = new UFvertex(i, 1);
            }
            foreach (Edge e in Edges)
            {
                UnionFind.Union(e, uf);
            }
            foreach (UFvertex uv in uf)
            {
                for (int i = 0; i < uf.Length; i++)
                {
                    comps.Add(uf[i].parent);
                    components[i] = uf[i].parent;
                }
            }

            NumberOfComponents = comps.Count;
            ComponentNumbers   = components;
            return(comps.Count);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// This method finds minimum spanning tree of an input graph
        /// </summary>
        /// <returns>
        /// It returns instance of SpanningTreeInfo class, that contains
        /// cost of MST and MST graph itself.
        /// </returns>
        /// <param name="g"> Is a graph in which MST will be found </param>
        public static SpanningTreeInfo GetSpanning(Graph g)
        {
            List <List <Edge> > graph = g.graph;
            // List of all graph edges
            List <Edge> edges = new List <Edge>();

            // For every vertex there is union-find representation for it
            UFvertex [] parents = new UFvertex[graph.Count];

            // Actual MST
            Graph mst = new Graph();

            // Edges that are used in MST
            long totalCost = 0;

            for (int i = 0; i < graph.Count; i++)
            {
                mst.AddVertex();
                parents[i] = new UFvertex(i, 1);
            }
            // Get all edges
            foreach (List <Edge> l in graph)
            {
                foreach (Edge e in l)
                {
                    edges.Add(e);
                }
            }

            // Sort all edges
            edges.Sort(comparison);
            foreach (Edge e in edges)
            {
                /* If union happened, that means that current edge connected
                 * together two components of a graph so it is added into MST */
                if (UnionFind.Union(e, parents))
                {
                    mst.AddEdge(e.source, e.destination, e.weight);
                    totalCost += e.weight;
                    /* Console.WriteLine("Hrana z {0} do {1}", e.source, e.destination); */
                }
            }
            return(new SpanningTreeInfo(mst, totalCost));
        }