/// <summary> /// Merge treeFrom with treeTo (this) /// Copy all vertices over /// Copy all edges over /// </summary> /// <param name="treeFrom">tree we are merging in</param> private void MergeTrees(AGraph <T> treeFrom) { foreach (Vertex <T> v in treeFrom.EnumerateVertices()) { this.AddVertex(v.Data); //this.AddVertexAdjustEdges(v); } foreach (Edge <T> e in treeFrom.GetAllEdges()) { this.AddEdge(e.From.data, e.To.data, e.Weight); } }
public IGraph <T> MinimumSpanningTree() { //Need to create an instance of the child class within the parent class. Don't know which child to create //Possible Solutions //1 - Create an abstract method where the child can return an instance of itself //2 - Use C# Reflection to return an instance of the child utilizing the GetType() AGraph <T> aGraph = null; List <AGraph <T> > forest = new List <AGraph <T> >(); EdgeComparer comparer = new EdgeComparer(); List <Edge <T> > liEdges = new List <Edge <T> >(); Edge <T>[] edges = this.GetAllEdges(); foreach (Edge <T> e in edges) { liEdges.Add(e); } liEdges.Sort(comparer); foreach (Vertex <T> v in vertices) { aGraph = (AGraph <T>)GetType().Assembly.CreateInstance(this.GetType().FullName); aGraph.AddVertex(v.Data); forest.Add(aGraph); } //while(liEdges.Count > 0 && forest.Count > 1) //{ foreach (Edge <T> e in liEdges) { int fromIndex = forest.FindIndex(g => g.vertices.Contains(e.From)); int toIndex = forest.FindIndex(g => g.vertices.Contains(e.To)); if (fromIndex != toIndex && fromIndex != -1 && toIndex != -1) { forest[fromIndex].MergeTrees(forest[toIndex]); forest[fromIndex].AddEdge(e.From.Data, e.To.Data, e.Weight); forest.RemoveAt(toIndex); } } //} if (forest.Count == 1) { aGraph = forest[0]; } return(aGraph); }
/// <summary> /// Given the forest (array of graphs), remove the location indicated by treeCut /// </summary> /// <param name="treeCut">Index of item to remove</param> /// <param name="forest">Array of graphs</param> /// <returns></returns> private AGraph <T> [] Timber(int treeCut, AGraph <T>[] forest) { AGraph <T>[] tempForest = new AGraph <T> [forest.Length - 1]; int j = 0; //Loop counter for the new forest for (int i = 0; i < forest.Length; i++) { if (i != treeCut) { tempForest[j++] = forest[i]; } } return(tempForest); }