Posts

Showing posts from January, 2022

BFS - Breadth First Search

The below is sample code to iterate through graph nodes using breadth first search - //build graph nodes var tree = new Dictionary<int, List<int>>(); tree.Add(1, new List<int> { 2, 3, 4 }); tree.Add(2, new List<int> { 5 }); tree.Add(3, new List<int> { 6, 7}); tree.Add(4, new List<int> { 8 }); tree.Add(5, new List<int> { 9 }); tree.Add(6, new List<int> { 10 }); //get root element of graph Queue q = new Queue(); q.Enqueue(tree.ElementAt(0).Key); HashSet<int> visitiedNode = new HashSet<int>(); //iterate queue to visit nodes while(q.Count > 0) { //dequeue 1st element var item = Convert.ToInt32(q.Dequeue()); //check if element already visited if (visitiedNode.Contains(item)) continue; //add element to visited list visitiedNode.Add(item); Console.WriteLine(item); //get next adjecent nodes tree.TryGetValue(item, out List<int> adjcentNodes); //enqueue new nodes to the queue if (adjcentNodes != null)