DFS Depth First Search on Graph in DSA C++ - Time & Space Complexity
We want to understand how the time taken by Depth First Search (DFS) changes as the graph size grows.
Specifically, how does DFS's work increase when the graph has more nodes and edges?
Analyze the time complexity of the following DFS code on a graph.
void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
visited[node] = true;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited);
}
}
}
This code visits each node and explores all its neighbors recursively.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop over neighbors inside the dfs function.
- How many times: Each edge is checked once, and each node is visited once.
As the graph grows, DFS 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.
Time Complexity: O(n + m)
This means DFS takes time proportional to the number of nodes plus the number of edges in the graph.
[X] Wrong: "DFS always takes O(n²) time because it uses recursion inside a loop."
[OK] Correct: DFS visits each node and edge only once, so it does not repeat work unnecessarily. The recursion just helps explore neighbors efficiently.
Understanding DFS time complexity helps you explain how graph traversal scales, a key skill in many coding challenges and real-world problems.
"What if the graph is represented as an adjacency matrix instead of adjacency lists? How would the time complexity change?"
Practice
Solution
Step 1: Understand DFS traversal
DFS explores a graph by going deep into one branch before backtracking to explore other branches.Step 2: Compare with other traversal methods
BFS visits neighbors first, but DFS goes deep first, matching Explore as far as possible along each branch before backtracking.Final Answer:
Explore as far as possible along each branch before backtracking -> Option AQuick Check:
DFS = deep exploration first [OK]
- Confusing DFS with BFS
- Thinking DFS visits neighbors first
- Assuming DFS visits nodes by distance
Solution
Step 1: Check typical DFS function signature
Usually, DFS is called as dfs(node, visited, graph) where node is current node.Step 2: Match the correct order
dfs(0, visited, graph); matches the common order: dfs(0, visited, graph).Final Answer:
dfs(0, visited, graph); -> Option BQuick Check:
Call dfs with node first [OK]
- Swapping argument order
- Using uppercase DFS instead of dfs
- Passing graph before node
Graph adjacency list: 0: [1, 2] 1: [3] 2: [] 3: []Assuming DFS visits neighbors in ascending order.
Solution
Step 1: Start DFS at node 0
Visit 0, then explore neighbors in ascending order: 1, then 2.Step 2: Explore neighbor 1
From 1, visit 3 (only neighbor), then backtrack.Step 3: Explore neighbor 2
Node 2 has no neighbors, so visit and backtrack.Final Answer:
[0, 1, 3, 2] -> Option CQuick Check:
DFS order = 0,1,3,2 [OK]
- Visiting node 2 before node 1
- Not backtracking properly
- Confusing BFS order with DFS
void dfs(int node, vector<bool> &visited, vector &graph) {
visited[node] = true;
for (int i = 0; i < graph[node].size(); i++) {
int neighbor = graph[node][i];
if (visited[neighbor] = false) {
dfs(neighbor, visited, graph);
}
}
}Solution
Step 1: Check the if condition inside the loop
The condition uses '=' which assigns false instead of comparing.Step 2: Understand the impact of assignment in condition
This causes the condition to always be false, so DFS won't recurse properly.Final Answer:
The condition 'if (visited[neighbor] = false)' uses assignment instead of comparison -> Option DQuick Check:
Use '==' for comparison, not '=' [OK]
- Using '=' instead of '==' in conditions
- Loop boundary off-by-one errors
- Passing visited by value causing no effect
Solution
Step 1: Understand counting reachable nodes
Counting nodes visited during DFS means incrementing a counter when marking a node visited.Step 2: Why other options fail
Counting nodes with no neighbors or summing degrees won't give reachable count; BFS is alternative but not required.Final Answer:
Add a counter variable incremented each time a node is visited during DFS -> Option AQuick Check:
Count nodes when visited in DFS [OK]
- Counting nodes with no neighbors instead of visited
- Using BFS unnecessarily
- Summing degrees instead of counting visited
Ready to prove it?
Pass the test and this pattern moves unknown
