C# Graph Traversal

后端 未结 4 1172
刺人心
刺人心 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:29

    Keep track of the predecessor nodes. In the easiest implementation, this is a dictionary, and usually denoted as π in pseudo-codes:

    Dictionary visited = new Dictionary();
    Dictionary π = new Dictionary();
    
    Queue worklist = new Queue();
    
    visited.Add(this, false);
    
    worklist.Enqueue(this);
    
    while (worklist.Count != 0)
    {
        Node node = worklist.Dequeue();
    
        foreach (Node neighbor in node.Neighbors)
        {
            if (!visited.ContainsKey(neighbor))
            {
                visited.Add(neighbor, false);
                π.Add(neighbor, node);
                worklist.Enqueue(neighbor);
            }
        }
    }
    

    Then you can iterate through these predecessors to backtrack the path from any node, say e:

    while (π[e] != null) {
        Console.WriteLine(e);
        e = π[e];
    }
    

提交回复
热议问题