Skip to content

Instantly share code, notes, and snippets.

@scalvert
Forked from riyadparvez/BFS.cs
Last active December 30, 2019 15:31
Show Gist options
  • Save scalvert/d9259a8f17d76b6e4032 to your computer and use it in GitHub Desktop.
Save scalvert/d9259a8f17d76b6e4032 to your computer and use it in GitHub Desktop.
public class Tree<K, V>
where K : class, IComparable<K>
where V : class
{
private Node<K, V> root;
public V BreadthFirstSearch(K key)
{
Queue<Node<K, V>> queue = new Queue<Node<K, V>>();
root.Visited = true;
queue.Enqueue(root);
while(queue.Any())
{
var node = queue.Dequeue();
if (node.Key == key)
{
return node.Value;
}
foreach (var child in node.GetAdjacentUnvisitedNodes())
{
child.Visited = true;
queue.Enqueue(child);
}
}
return default(V);
}
private class Node<K, V>
where K : class, IComparable<K>
where V : class
{
public K Key { get; set; }
public V Value { get; set; }
public bool Visited { get; set; }
public IList<Node<K, V>> Nodes { get; set; }
public IList<Node<K, V>> GetAdjacentUnvisitedNodes()
{
return this.Nodes.Where(n => !n.Visited);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment