This algorithm does a great job of traversing the nodes in a graph.
Dictionary visited = new Dictionary();
Queue
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];
}