Esempio n. 1
0
        /// <summary>
        /// constructs a sub-tree
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="visitedEdges"></param>
        /// <param name="startEdge"></param>
        /// <returns></returns>
        private MinimumSpanningTree <T> ConstructSubTree(FeatureGraph <T> graph,
                                                         HashSet <int> visitedEdges,
                                                         Edge <T> startEdge)
        {
            // Manages the tree being constructed.
            var tree = new MinimumSpanningTree <T>();

            // Manages the list of candidate edges
            var tempEdges = new UniqueEdgeList <T>();

            // Seed of the breadth first search (BFS)
            tempEdges.AddEdge(startEdge);

            // Start BFS
            while (tempEdges.Count > 0)
            {
                // Sort the edges based on distace.
                tempEdges.Sort();

                Edge <T> shortestEdge  = null;
                var      edgesToRemove = new List <Edge <T> >();

                // Find the shortest edge...
                foreach (var edge in tempEdges.Edges)
                {
                    var edgeSeen   = tree.HasEdgeBeenSeen(edge);
                    var vertexSeen = tree.HasEdgeVerticesBeenSeen(edge);

                    // Make sure that we havent seen this edge.
                    if (edgeSeen)
                    {
                        continue;
                    }

                    if (vertexSeen)
                    {
                        visitedEdges.Add(edge.ID);
                        edgesToRemove.Add(edge);
                        continue;
                    }

                    shortestEdge = edge;
                    tree.AddEdge(shortestEdge);
                    break;
                }

                // Remove any edges that have been used up..
                edgesToRemove.ForEach(x => tempEdges.RemoveEdge(x));
                edgesToRemove.ForEach(x => graph.RemoveEdge(x));

                // We didnt find an edge, so we have nothing else to connect...
                if (shortestEdge == null)
                {
                    // Make sure that we assert that there are no edges left...should be the case here!
                    System.Diagnostics.Debug.Assert(tempEdges.Count == 0);
                    break;
                }

                visitedEdges.Add(shortestEdge.ID);

                // Removes the shortest edge from the graph...
                graph.RemoveEdge(shortestEdge);

                var adjacentEdges = graph.GetAdjacentEdgesFromEdgeVertices(shortestEdge);
                //adjacentEdges.Sort();

                tempEdges.AddEdges(adjacentEdges.Edges);

                // Remove the shortest edge from the list of available edges left...
                tempEdges.RemoveEdge(shortestEdge);
            }

            return(tree);
        }