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.
How does DFS's work increase when the graph has more nodes and edges?
Analyze the time complexity of the following code snippet.
void dfs(int node, int visited[], int graph[][N], int n) {
visited[node] = 1;
for (int i = 0; i < n; i++) {
if (graph[node][i] == 1 && !visited[i]) {
dfs(i, visited, graph, n);
}
}
}
This code visits all nodes reachable from the starting node using DFS on an adjacency matrix graph.
- Primary operation: The for-loop inside dfs that checks all possible neighbors of the current node.
- How many times: This loop runs for each node visited, and dfs is called recursively for each unvisited neighbor.
As the number of nodes (n) increases, DFS visits each node once and performs n neighbor checks for each visited node (adjacency matrix).
| Input Size (n) | Approx. Operations |
|---|---|
| 10 nodes | About 100 operations (10 × 10 checks) |
| 100 nodes | About 10,000 operations (100 × 100) |
| 1000 nodes | About 1,000,000 operations (1000 × 1000) |
Pattern observation: Operations grow quadratically with the number of nodes, so more nodes mean much more work.
Time Complexity: O(n^2)
This means DFS takes time proportional to the square of the number of nodes in the graph.
[X] Wrong: "DFS takes O(n + e) time because each edge is checked once."
[OK] Correct: The nested loop is inside recursion, but for adjacency matrix, the loop scans all n columns for each of the n nodes, so total work is O(n^2), not dependent on e.
Understanding DFS time complexity helps you explain how graph traversal scales, a key skill in many coding problems and interviews.
"What if the graph was represented using adjacency lists instead of an adjacency matrix? 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 others.Step 2: Compare with other traversal methods
BFS visits nodes level by level, but DFS goes deep first.Final Answer:
Explore as far as possible along each branch before backtracking -> Option CQuick Check:
DFS = deep exploration first [OK]
- Confusing DFS with BFS
- Thinking DFS visits nodes level-wise
- Assuming DFS visits nodes randomly
adj and visited array visited?Solution
Step 1: Mark current node as visited
Set visited[node] = 1 (or true) to avoid revisiting.Step 2: Traverse neighbors only if not visited
Check if neighbor is unvisited before recursive DFS call to prevent infinite loops.Final Answer:
void dfs(int node) { visited[node] = 1; for(int i=0; i -> Option DQuick Check:
Mark visited and check before recursion [OK]
- Not checking if neighbor is visited
- Using wrong visited value (0 instead of 1)
- Using .size() instead of .length in C arrays
0: [1, 2]
1: [2]
2: [0, 3]
3: [3]Starting DFS from node 2, what is the order of nodes visited?
Solution
Step 1: Start DFS at node 2
Visit 2, mark visited. Neighbors: 0 and 3.Step 2: Visit neighbor 0 first
From 2, go to 0. Visit 0, neighbors: 1 and 2 (2 already visited).Step 3: Visit neighbor 1 from 0
Visit 1, neighbor: 2 (visited). Backtrack.Step 4: Back to 2, visit neighbor 3
Visit 3, neighbor: 3 (already visited). End.Final Answer:
[2, 0, 1, 3] -> Option BQuick Check:
DFS order from 2 = [2,0,1,3] [OK]
- Visiting nodes multiple times
- Visiting neighbors in wrong order
- Ignoring visited checks causing loops
void dfs(int node) {
visited[node] = 1;
for(int i=0; i<adj[node].length; i++) {
dfs(adj[node][i]);
}
}Solution
Step 1: Analyze DFS recursion calls
The code calls dfs on all neighbors without checking if they are visited.Step 2: Identify risk of infinite recursion
Without visited check, DFS may revisit nodes endlessly causing stack overflow.Final Answer:
Missing check if neighbor is already visited before recursive call -> Option AQuick Check:
Always check visited before recursion [OK]
- Assuming visited check is optional
- Setting visited after recursion
- Ignoring infinite recursion risk
Solution
Step 1: Understand cycle detection in DFS
Detect cycles by tracking nodes currently in recursion (call) stack.Step 2: Use recursion stack array
Maintain an array marking nodes in current DFS path; if a neighbor is in this stack, a cycle exists.Step 3: Differentiate from visited array
Visited marks all visited nodes; recursion stack tracks current path only.Final Answer:
Use a recursion stack array to track nodes in the current path and check if a node is revisited in this stack -> Option AQuick Check:
Recursion stack detects cycles in DFS [OK]
- Confusing visited with recursion stack
- Using BFS for cycle detection in directed graphs
- Not tracking current path nodes
Ready to prove it?
Pass the test and this pattern moves unknown
