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)
		adjcentNodes.ForEach(a => q.Enqueue(a));
}

This code iterates through each node and can be modified to check on given key.

Comments

Popular posts from this blog

Windows Azure Package Build Error: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Resource ID : 1. The request limit for the database is 180 and has been reached.

How to get Client's Location using IPAddress