Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Last active March 19, 2024 20:44
Show Gist options
  • Save riyadparvez/5915090 to your computer and use it in GitHub Desktop.
Save riyadparvez/5915090 to your computer and use it in GitHub Desktop.
An implementation of breadth first search or BFS in C#.
public class Tree<K, V>
where K : class, IComparable<K>
where V : class
{
private Node<K, V> root;
public V BFS(K key)
{
Queue<Node<K, V>> queue = new Queue<Node<K, V>>();
while(queue.Any())
{
var node = queue.Dequeue();
if(node.key == key)
{
return node.value;
}
foreach (var child in node.children)
{
queue.Enqueue(child);
}
}
return default(V);
}
private class Node<K, V>
where K : class, IComparable<K>
where V : class
{
public K key;
public V value;
public Node<K, V>[] children;
}
}
@BethesdaOwuama
Copy link

Type parameter K has the same type parameter from outer part <K,V>

@mohammaddabiri
Copy link

Line 10 should say queue.Enqueue(rootNode);

@nam20485
Copy link

nam20485 commented Mar 19, 2024

FTFY. Credit due to suggestions from other comments.

public class Tree<K, V>
    where K : class, IComparable<K>
    where V : class
{
    private Node<K, V> root;

    public V BFS(K key)
    {
        Queue<Node<K, V>> queue = new Queue<Node<K, V>>();
        // collection of visited nodes
        HashSet<Node<K, V>> visited = new HashSet<Node<K, V>>();

        // start with "first" node
        queue.Enqueue(root);
        visited.Add(root);

        while (queue.Any())
        {
            var node = queue.Dequeue();

            if (node.key == key)
            {
                return node.value;
            }
            foreach (var child in node.children)
            {
                // only add child node if it has not already been visited
                if (!visited.Contains(child))
                {
                    // mark child node visited
                    visited.Add(child);
                    queue.Enqueue(child);
                }
            }
        }
        return default(V);
    }

    private class Node<K, V>
        where K : class, IComparable<K>
        where V : class
    {
        public K key;
        public V value;
        public Node<K, V>[] children;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment