QuickGraph - is there algorithm for find all parents (up to root vertex's) of a set of vertex's

前端 未结 3 1215
既然无缘
既然无缘 2021-01-13 15:56

In QuickGraph - is there algorithm for find all parents (up to root vertex\'s) of a set of vertex\'s. In other words all vertex\'s which have somewhere under them (on the w

3条回答
  •  粉色の甜心
    2021-01-13 16:48

    Here's what I've used to accomplish a predecessor search on a given vertex:

    IBidirectionalGraph> CreateGraph(int vertexCount)
    {
        BidirectionalGraph> graph = new BidirectionalGraph>(true);
        for (int i = 0; i < vertexCount; i++)
            graph.AddVertex(i);
    
        for (int i = 1; i < vertexCount; i++)
            graph.AddEdge(new Edge(i - 1, i));
    
        return graph;
    }
    
    static public void Main()
    {
        IBidirectionalGraph> graph = CreateGraph(5);
    
        var dfs = new DepthFirstSearchAlgorithm>(graph);            
        var observer = new VertexPredecessorRecorderObserver>();
    
        using (observer.Attach(dfs)) // attach, detach to dfs events
            dfs.Compute();
    
        int vertexToFind = 3;
        IEnumerable> edges;
        if (observer.TryGetPath(vertexToFind, out edges))
        {
            Console.WriteLine("To get to vertex '" + vertexToFind + "', take the following edges:");
            foreach (IEdge edge in edges)
                Console.WriteLine(edge.Source + " -> " + edge.Target);
        }
    }
    

    Note that if you know your root beforehand, you can specify it in the dfs.Compute() method (i.e. dfs.Compute(0)).

    -Doug

提交回复
热议问题