C# Graph Traversal

后端 未结 4 1126
刺人心
刺人心 2021-02-02 00:45

This algorithm does a great job of traversing the nodes in a graph.

Dictionary visited = new Dictionary();

Queue         


        
4条回答
  •  死守一世寂寞
    2021-02-02 01:28

    Is "this", that is, the current instance, the "root" of the graph, if there is such a thing?

    Is the graph cyclic or acyclic? I'm afraid I don't know all the terms for graph theory.

    Here's what I really wonder about:

    A -> B -> C ------> F
         B -> D -> E -> F
    

    Here are my questions:

    • Will this occur?
    • Can "this" in your code ever start at B?
    • What will the path to F be?

    If the graph never joins back together when it has split up, doesn't contain cycles, and "this" will always be the root/start of the graph, a simple dictionary will handle the path.

    Dictionary PreNodes = new Dictionary();
    

    for each node you visit, add the neighbouring node as key, and the node it was a neighbour of as the value. This will allow you to, once you've find the target node, to backtrack back to get the reversed path.

    In other words, the dictionary for the graph above, after a full traversal would be:

    B: A
    C: B
    D: B
    E: D
    F: C (or E, or both?)
    

    To find the path to the E-node, simply backtrack:

    E -> D -> B -> A
    

    Which gives you the path:

    A -> B -> D -> E
    

提交回复
热议问题