簡體   English   中英

QuickGraph - 是否有算法用於查找一組頂點的所有父項(直到根頂點)

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

在QuickGraph中 - 是否有算法用於查找一組頂點的所有父項(直到根頂點)。 換句話說,所有頂點都位於它們下面(在去往葉節點的路上)一個或多個頂點輸入。 因此,如果頂點是節點,並且邊緣取決於關系,則查找將受給定節點集影響的所有節點。

如果沒有寫出自己的算法有多難?

我使用Doug的答案,發現如果頂點有多個父級,他的解決方案只提供一個父級。 我不知道為什么。

所以,我創建了自己的版本,如下所示:

    public IEnumerable<T> GetParents(T vertexToFind)
    {
        IEnumerable<T> parents = null;

        if (this.graph.Edges != null)
        {
            parents = this.graph
                .Edges
                .Where(x => x.Target.Equals(vertexToFind))
                .Select(x => x.Source);
        }

        return parents;
    }

這是我用來完成給定頂點上的前任搜索:

IBidirectionalGraph<int, IEdge<int>> CreateGraph(int vertexCount)
{
    BidirectionalGraph<int, IEdge<int>> graph = new BidirectionalGraph<int, IEdge<int>>(true);
    for (int i = 0; i < vertexCount; i++)
        graph.AddVertex(i);

    for (int i = 1; i < vertexCount; i++)
        graph.AddEdge(new Edge<int>(i - 1, i));

    return graph;
}

static public void Main()
{
    IBidirectionalGraph<int, IEdge<int>> graph = CreateGraph(5);

    var dfs = new DepthFirstSearchAlgorithm<int, IEdge<int>>(graph);            
    var observer = new VertexPredecessorRecorderObserver<int, IEdge<int>>();

    using (observer.Attach(dfs)) // attach, detach to dfs events
        dfs.Compute();

    int vertexToFind = 3;
    IEnumerable<IEdge<int>> edges;
    if (observer.TryGetPath(vertexToFind, out edges))
    {
        Console.WriteLine("To get to vertex '" + vertexToFind + "', take the following edges:");
        foreach (IEdge<int> edge in edges)
            Console.WriteLine(edge.Source + " -> " + edge.Target);
    }
}

請注意,如果您事先知道根,則可以在dfs.Compute()方法中指定它(即dfs.Compute(0) )。

-Doug

您需要維護反轉圖形,或者在圖形上創建一個反轉每個邊緣的包裝器。 QuickGraph有ReversedBidirectionalGraph類,它是一個專門用於它的包裝器,但由於泛型類型不兼容,它似乎不適用於算法類。 我必須創建自己的包裝類:

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

然后在此包裝器上運行DFS或BFS:

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

道格的答案是不正確的,因為DFS只會訪問下游子圖。 前任觀察員沒有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM