Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Depth first search using Queue

How do I do a depth first search using a Queue in c#?

The following is my datastructure:

public class Node
{
  public string Name{get;set}
  public IEnumerable<Node> Children{get;set;}
}

Now I have a collection of Node object each with children, which again has children and so on.

I want to access each node and convert it into a different form.

Something like the below:

public IEnumerable<IContent> BuildContentFrom(IEnumerable<Node> nodes)
        {
            var queue = new Queue<Node>(nodes);

            while (queue.Any())
            {
                var next = queue.Dequeue();
                yield return BuildContentFromSingle(next);

                foreach (var child in next.Children)
                {
                    queue.Enqueue(child);
                }
            }
        }

        public IContent BuildContentFromSingle(Node node)
        {
            var content = _contentFactory.Create(node);
            return content;
        }  

The above does not give me depth first for some reason. Can you please help?

like image 848
Mike Avatar asked Jan 14 '23 04:01

Mike


1 Answers

Depth-first search is implemented using a LIFO data structure, so you 'd need to swap the Queue for a Stack. Using a FIFO structure like a queue gives you BFS instead.

like image 198
Jon Avatar answered Jan 28 '23 06:01

Jon