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 hidden or 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FTFY. Credit due to suggestions from other comments.