Search⌘ K
AI Features

Solution Review: Implement Breadth First Search

Explore how to implement Breadth First Search on graphs using a queue. Understand the traversal process that visits nodes level by level, tracking visited vertices and managing adjacency. Gain insight into BFS's time complexity and practical application in graph algorithms.

We'll cover the following...

Solution: Using queues

C#
using System;
using System.Collections.Generic;
namespace chapter_5
{
class Challenge_1
{
static void bfsTraversal_helper(Graph g, int source, bool[] visited, ref string result)
{
if (g.getVertices() < 1)
{
return;
}
//Create Queue(Implemented in previous chapters) for Breadth First Traversal and enqueue source in it
//myQueue queue(g.getVertices());
Queue<int> queue = new Queue<int> { };
queue.Enqueue(source);
visited[source] = true;
int current_node;
//Traverse while queue is not empty
while (queue.Count != 0)
{
//Dequeue a vertex/node from queue and add it to result
current_node = queue.Dequeue();
result += current_node.ToString();
//Get adjacent vertices to the current_node from the array,
//and if they are not already visited then enqueue them in the Queue
LinkedList.Node temp = (g.getArray())[current_node].GetHead();
while (temp != null)
{
if (!visited[temp.data])
{
queue.Enqueue(temp.data);
visited[temp.data] = true; //Visit the current Node
}
temp = temp.nextElement;
}
} //end of while
}
static string bfsTraversal(Graph g)
{
string result = "";
//Bool Array to hold the history of visited nodes
//Make a node visited whenever you push it into stack
bool[] visited = new bool[g.getVertices()];
for (int i = 0; i < g.getVertices(); i++)
{
visited[i] = false;
}
for (int i = 0; i < g.getVertices(); i++)
{
if (!visited[i])
bfsTraversal_helper(g, i, visited, ref result);
}
visited = null;
return result;
}
static void Main(string[] args)
{
Graph g = new Graph(6);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.addEdge(2, 5);
Console.WriteLine(bfsTraversal(g));
}
}
}

For this solution, you will use the help of the queue data structure studied earlier. bfsTraversal calls the helper function bfs_helper on every ...