Shortest Path in Unweighted Graph Using BFS in DSA C++ - Time & Space Complexity
We want to know how long it takes to find the shortest path in an unweighted graph using BFS.
Specifically, how the time grows as the graph gets bigger.
Analyze the time complexity of the following code snippet.
void bfsShortestPath(int start, vector<vector<int>> &graph, vector<int> &dist) {
int n = graph.size();
queue<int> q;
dist.assign(n, -1);
dist[start] = 0;
q.push(start);
while (!q.empty()) {
int node = q.front(); q.pop();
for (int neighbor : graph[node]) {
if (dist[neighbor] == -1) {
dist[neighbor] = dist[node] + 1;
q.push(neighbor);
}
}
}
}
This code finds the shortest distance from a start node to all other nodes in an unweighted graph using BFS.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Visiting each node and checking its neighbors in the graph.
- How many times: Each node is visited once, and each edge is checked once during the BFS traversal.
As the graph grows, the BFS visits every node and edge once.
| Input Size (n nodes, m edges) | Approx. Operations |
|---|---|
| 10 nodes, 15 edges | About 25 operations (10 nodes + 15 edges) |
| 100 nodes, 200 edges | About 300 operations (100 + 200) |
| 1000 nodes, 5000 edges | About 6000 operations (1000 + 5000) |
Pattern observation: The operations grow roughly in proportion to the number of nodes plus edges.
Time Complexity: O(n + m)
This means the time grows linearly with the number of nodes and edges in the graph.
[X] Wrong: "BFS takes O(n²) time because it uses nested loops."
[OK] Correct: BFS visits each node and edge only once, so it does not repeatedly check all pairs. The loops are not nested over all nodes but over neighbors, which sums to edges.
Understanding BFS time complexity helps you explain why it is efficient for shortest paths in unweighted graphs, a common interview topic.
"What if the graph was represented using an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand BFS traversal
BFS explores nodes level by level starting from the source node.Step 2: BFS finds shortest paths in unweighted graphs
Because BFS visits nodes in order of increasing distance, it finds shortest paths from source to all nodes.Final Answer:
To find the shortest path from a source node to all other nodes -> Option CQuick Check:
BFS shortest path = D [OK]
- Confusing BFS with DFS for shortest path
- Thinking BFS finds maximum depth
- Assuming BFS sorts nodes topologically
Solution
Step 1: Identify correct queue declaration
In C++, BFS uses std::queue with push() to add elements.Step 2: Check method names
push() is correct for queue; insert() and add() are invalid; stack is wrong data structure.Final Answer:
queue<int> q; q.push(0); -> Option AQuick Check:
queue push() method = C [OK]
- Using stack instead of queue
- Using insert() or add() instead of push()
- Confusing queue methods with vector methods
int n = 4;
vector adj = {{1,2}, {0,2,3}, {0,1,3}, {1,2}};
vector<int> dist(n, -1);
queue<int> q;
dist[0] = 0;
q.push(0);
while(!q.empty()) {
int u = q.front(); q.pop();
for(int v : adj[u]) {
if(dist[v] == -1) {
dist[v] = dist[u] + 1;
q.push(v);
}
}
}
for(int i=0; iWhat is the output?Solution
Step 1: Initialize distances and start BFS
dist[0]=0, others -1; start from node 0.Step 2: BFS visits neighbors and updates distances
From 0: neighbors 1,2 get dist=1; from 1 and 2: neighbor 3 gets dist=2.Final Answer:
0 1 1 2 -> Option AQuick Check:
BFS distance array = 0 1 1 2 [OK]
- Mixing up node indices and distances
- Not initializing distances to -1
- Forgetting to check if node was visited
int n = 3;
vector adj = {{1}, {0,2}, {1}};
vector<int> dist(n, 0);
queue<int> q;
dist[0] = 0;
q.push(0);
while(!q.empty()) {
int u = q.front(); q.pop();
for(int v : adj[u]) {
if(dist[v] == 0) {
dist[v] = dist[u] + 1;
q.push(v);
}
}
}
for(int i=0; iSolution
Step 1: Check distance initialization
dist initialized with 0 means unvisited nodes are indistinguishable from source.Step 2: Identify impact on BFS logic
Condition dist[v] == 0 fails to detect unvisited nodes correctly, causing wrong or no updates.Final Answer:
dist vector initialized with 0 instead of -1 -> Option DQuick Check:
dist init must be -1 to mark unvisited [OK]
- Using 0 as unvisited marker
- Not checking visited condition properly
- Misusing queue operations
Solution
Step 1: Build graph and run BFS from node 0
Edges: 0-1,0-2; 1-3; 2-3; 3-4. BFS levels: 0(dist=0), 1 and 2(dist=1), 3(dist=2), 4(dist=3).Step 2: Identify shortest path to node 4
Shortest distance to 4 is 3. Paths: 0->1->3->4 or 0->2->3->4. Distance: 3; Path: 0 -> 2 -> 3 -> 4 shows correct distance and one valid path.Final Answer:
Distance: 3; Path: 0 -> 2 -> 3 -> 4 -> Option BQuick Check:
Shortest path length = 3 via node 2 [OK]
- Assuming direct edge from 0 to 3
- Confusing distance with number of edges
- Ignoring multiple shortest paths
Ready to prove it?
Pass the test and this pattern moves unknown
