Last active
March 19, 2024 20:44
-
-
Save riyadparvez/5915090 to your computer and use it in GitHub Desktop.
An implementation of breadth first search or BFS in C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Line 10 should say queue.Enqueue(rootNode);
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
Type parameter K has the same type parameter from outer part <K,V>