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

前端 未结 3 1224
既然无缘
既然无缘 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:52

    You either need to maintain a reversed graph, or create a wrapper over the graph that reverses every edge. QuickGraph has the ReversedBidirectionalGraph class that is a wrapper intended just for that, but it does not seem to work with the algorithm classes because of generic type incompatibility. I had to create my own wrapper class:

    class ReversedBidirectionalGraphWrapper : IVertexListGraph where TEdge : IEdge 
    {
      private BidirectionalGraph _originalGraph;
      public IEnumerable OutEdges(TVertex v)
        {
            foreach (var e in _graph.InEdges(v))
            {
                yield return (TEdge)Convert.ChangeType(new Edge(e.Target, e.Source), typeof(TEdge));
            }
        } //...implement the rest of the interface members using the same trick
    }
    

    Then run DFS or BFS on this wrapper:

    var w = new ReversedBidirectionalGraphWrapper>(graph);    
    var result = new List();    
    var alg = new DepthFirstSearchAlgorithm>(w);
    alg.TreeEdge += e => result.Add(e.Target);    
    alg.Compute(node);
    

    Doug's answer is not correct, because DFS will only visit the downstream subgraph. The predecessor observer does not help.

提交回复
热议问题