BFS Breadth First Search on Graph in DSA C# - Time & Space Complexity
We want to understand how the time needed to explore a graph grows as the graph gets bigger using BFS.
How does BFS's work change when the graph has more nodes and edges?
Analyze the time complexity of the following code snippet.
// BFS on a graph using adjacency list
void BFS(int start, List<int>[] graph) {
bool[] visited = new bool[graph.Length];
Queue<int> queue = new Queue<int>();
visited[start] = true;
queue.Enqueue(start);
while (queue.Count > 0) {
int node = queue.Dequeue();
foreach (int neighbor in graph[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
queue.Enqueue(neighbor);
}
}
}
}
This code explores all nodes reachable from the start node using BFS on a graph represented by adjacency lists.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node and checking all its neighbors in the adjacency list.
- How many times: Each node is enqueued and dequeued once; each edge is checked once in the neighbor loops.
As the graph grows, BFS visits every node and edge once.
| Input Size (n nodes, m edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 10 + 15 = 25 operations |
| 100 nodes, 200 edges | About 100 + 200 = 300 operations |
| 1000 nodes, 5000 edges | About 1000 + 5000 = 6000 operations |
Pattern observation: The work grows roughly with the sum of nodes and edges, so more nodes or edges means more work.
Time Complexity: O(n + m)
This means BFS takes time proportional to the number of nodes plus the number of edges in the graph.
[X] Wrong: "BFS always takes O(n²) time because it uses nested loops."
[OK] Correct: BFS uses adjacency lists, so it only checks each edge once, not all pairs of nodes. The loops are not nested over all nodes but over neighbors, which keeps it efficient.
Understanding BFS time complexity helps you explain how graph searches scale and why BFS is efficient for many problems. This skill shows you can analyze algorithms clearly and confidently.
"What if the graph was represented by an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand BFS traversal method
BFS explores nodes level by level, visiting all neighbors before moving deeper.Step 2: Identify data structure used for level order traversal
To achieve level order, BFS uses a queue to process nodes in the order they are discovered.Final Answer:
A queue data structure -> Option DQuick Check:
BFS uses queue = A [OK]
- Confusing BFS with DFS which uses stack
- Thinking BFS uses priority queue
- Assuming BFS uses only a hash set
current in a BFS queue in C#?Solution
Step 1: Recall C# Queue methods
The Queue class in C# uses Enqueue() to add elements at the end.Step 2: Match method to enqueue operation
Push() is for stacks, Add() and Insert() are not Queue methods.Final Answer:
queue.Enqueue(current); -> Option AQuick Check:
Queue add method = Enqueue [OK]
- Using Push() which is for stacks
- Using Add() or Insert() which are not queue methods
- Confusing queue with list methods
var graph = new Dictionary {
{1, new List<int>{2, 3}},
{2, new List<int>{4}},
{3, new List<int>{4}},
{4, new List<int>{}}
};
Solution
Step 1: Start BFS from node 1
Visit 1, enqueue neighbors 2 and 3 in order.Step 2: Visit nodes in queue order
Dequeue 2, visit it, enqueue 4. Then dequeue 3, visit it, enqueue 4 (already enqueued).Step 3: Visit node 4
Dequeue 4, visit it. No new nodes to enqueue.Final Answer:
[1, 2, 3, 4] -> Option AQuick Check:
BFS order = [1, 2, 3, 4] [OK]
- Visiting neighbors in wrong order
- Visiting node 3 before 2
- Adding duplicates of node 4
var queue = new Queue<int>();
var visited = new HashSet<int>();
queue.Enqueue(1);
while(queue.Count > 0) {
int node = queue.Dequeue();
if(!visited.Contains(node)) {
visited.Add(node);
foreach(var neighbor in graph[node]) {
queue.Enqueue(neighbor);
}
}
}Solution
Step 1: Analyze neighbor enqueue logic
Neighbors are enqueued without checking if visited, causing duplicates.Step 2: Identify missing visited check before enqueue
Should check if neighbor is visited before enqueue to avoid repeated processing.Final Answer:
Neighbors are enqueued even if already visited -> Option CQuick Check:
Check visited before enqueue = D [OK]
- Enqueueing visited neighbors multiple times
- Not adding nodes to visited set
- Incorrect queue initialization
Solution
Step 1: Understand BFS for shortest path
BFS finds shortest paths in unweighted graphs by exploring neighbors level-wise.Step 2: Track path using parent dictionary
Store each node's parent when first visited to reconstruct path after BFS completes.Final Answer:
Maintain a dictionary to store each node's parent during traversal -> Option BQuick Check:
Parent tracking dictionary = C [OK]
- Using stack breaks BFS order
- Marking visited too late causes duplicates
- Enqueueing nodes multiple times wastes time
Ready to prove it?
Pass the test and this pattern moves unknown
