Tutorials Data Structures and Algorithms in C#
BFS on Graphs
BFS on Graphs: free step-by-step lesson with examples, common mistakes, and interview tips — part of Data Structures and Algorithms in C# on Toolliyo Academy.
On this page
Data Structures and Algorithms in C# · Lesson 62 of 120
BFS on Graphs
Foundations & Arrays ✓ → Lists, Hash, Trees ✓ → Graphs & DP → Advanced & Projects
Graphs & DP · 3 — Patterns · ~10 min · Graphs
What is this?
BFS explores neighbors level by level using a queue — shortest path in unweighted graphs.
Why should you care?
Grid problems, social “degrees”, and serialization often reduce to BFS.
See it live — copy this example
Run snippets in a .NET console app, LINQPad, or https://dotnetfiddle.net. Write Big O above every solution.
void Bfs(Dictionary<int, List<int>> g, int start) {
var q = new Queue<int>();
var seen = new HashSet<int> { start };
q.Enqueue(start);
while (q.Count > 0) {
int u = q.Dequeue();
Console.WriteLine(u);
foreach (var v in g.GetValueOrDefault(u, new()))
if (seen.Add(v)) q.Enqueue(v);
}
}
What happened?
- Queue stores frontier.
- HashSet prevents revisits.
- Add returns false if already present.
Practice next
- Build a tiny adjacency list.
- Run BFS from node 1.
- Track distance dictionary.
- Return parent pointers to reconstruct path.
- Multi-source BFS warm-up.
Remember
BFS = queue + visited. Unweighted shortest paths. Model the graph first.
Shortest hops
Friend-of-friend distance.
Outcome: BFS levels equal hop count.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!