Search⌘ K
AI Features

Challenge: Implement Breadth-First Graph Traversal

Explore how to implement breadth-first search traversal for graphs in C#. Learn to navigate graphs level by level using adjacency lists and appropriate data structures. This lesson helps you design an algorithm for BFS traversal and apply it in practice, reinforcing your understanding of graph algorithms for coding interviews.

Problem statement

We have to implement the breadth-first traversal in C#. It is a level-by-level searching algorithm for the graph, so we will use our already-implemented Graph class for this task (since we have already covered the implementation of the graph).

To solve this problem, all the previously implemented data structures will be available to us.

Input

A graph represented as an adjacency list and a starting vertex.

Output

A string containing the vertices of the graph listed in the correct order of traversal.

Sample input

Graph:

Vertex

Edges

0

2, 1

1

4, 3

2

None

3

None

4

None

Source: 0

Sample output

result = "02143";
or
result = "01234";

Traversal strategy: Print the right child first and then the left child.

canvasAnimation-image
1 / 6

Coding exercise

First, take a close look at this problem and design a step-by-step algorithm before jumping to the implementation. This problem is designed for your practice, so try to solve it on your own first. If you get stuck, you can always refer to the solution provided in the solution section. Good luck!

BFS
Graph.cs
class Program
{
/// <summary>
/// Method to print a BFS of a graph.
/// </summary>
/// <param name="graph">The graph.</param>
/// <param name="source">Starting vertex.</param>
public static string BFS(Graph myGraph, int source)
{
// Write your code here!
return string.Empty;
}
}