Bird
Raised Fist0
DSA Cprogramming~5 mins

DFS Depth First Search on Graph in DSA C - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: DFS Depth First Search on Graph
O(n^2)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

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 nodesAbout 100 operations (10 × 10 checks)
100 nodesAbout 10,000 operations (100 × 100)
1000 nodesAbout 1,000,000 operations (1000 × 1000)

Pattern observation: Operations grow quadratically with the number of nodes, so more nodes mean much more work.

Final Time Complexity

Time Complexity: O(n^2)

This means DFS takes time proportional to the square of the number of nodes in the graph.

Common Mistake

[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.

Interview Connect

Understanding DFS time complexity helps you explain how graph traversal scales, a key skill in many coding problems and interviews.

Self-Check

"What if the graph was represented using adjacency lists instead of an adjacency matrix? How would the time complexity change?"

Practice

(1/5)
1. What is the main idea behind Depth First Search (DFS) on a graph?
easy
A. Visit all nodes at the current depth before moving deeper
B. Visit nodes randomly without any order
C. Explore as far as possible along each branch before backtracking
D. Only visit nodes with no outgoing edges

Solution

  1. Step 1: Understand DFS traversal

    DFS explores a graph by going deep into one branch before backtracking to explore others.
  2. Step 2: Compare with other traversal methods

    BFS visits nodes level by level, but DFS goes deep first.
  3. Final Answer:

    Explore as far as possible along each branch before backtracking -> Option C
  4. Quick Check:

    DFS = deep exploration first [OK]
Hint: DFS means go deep first, then backtrack [OK]
Common Mistakes:
  • Confusing DFS with BFS
  • Thinking DFS visits nodes level-wise
  • Assuming DFS visits nodes randomly
2. Which of the following is the correct way to start a DFS function in C for a graph represented by adjacency list adj and visited array visited?
easy
A. void dfs(int node) { visited[node] = 1; for(int i=0; i
B. void dfs(int node) { visited[node] = true; for(int i=0; i
C. void dfs(int node) { visited[node] = 0; for(int i=0; i
D. void dfs(int node) { visited[node] = 1; for(int i=0; i

Solution

  1. Step 1: Mark current node as visited

    Set visited[node] = 1 (or true) to avoid revisiting.
  2. Step 2: Traverse neighbors only if not visited

    Check if neighbor is unvisited before recursive DFS call to prevent infinite loops.
  3. Final Answer:

    void dfs(int node) { visited[node] = 1; for(int i=0; i -> Option D
  4. Quick Check:

    Mark visited and check before recursion [OK]
Hint: Always check visited before recursive DFS call [OK]
Common Mistakes:
  • Not checking if neighbor is visited
  • Using wrong visited value (0 instead of 1)
  • Using .size() instead of .length in C arrays
3. Consider the following graph adjacency list:
0: [1, 2]
1: [2]
2: [0, 3]
3: [3]

Starting DFS from node 2, what is the order of nodes visited?
medium
A. [2, 3, 0, 1]
B. [2, 0, 1, 3]
C. [2, 0, 3, 1]
D. [2, 1, 0, 3]

Solution

  1. Step 1: Start DFS at node 2

    Visit 2, mark visited. Neighbors: 0 and 3.
  2. Step 2: Visit neighbor 0 first

    From 2, go to 0. Visit 0, neighbors: 1 and 2 (2 already visited).
  3. Step 3: Visit neighbor 1 from 0

    Visit 1, neighbor: 2 (visited). Backtrack.
  4. Step 4: Back to 2, visit neighbor 3

    Visit 3, neighbor: 3 (already visited). End.
  5. Final Answer:

    [2, 0, 1, 3] -> Option B
  6. Quick Check:

    DFS order from 2 = [2,0,1,3] [OK]
Hint: Follow neighbors depth-first, mark visited to avoid repeats [OK]
Common Mistakes:
  • Visiting nodes multiple times
  • Visiting neighbors in wrong order
  • Ignoring visited checks causing loops
4. The following DFS code has a bug. What is the error?
void dfs(int node) {
  visited[node] = 1;
  for(int i=0; i<adj[node].length; i++) {
    dfs(adj[node][i]);
  }
}
medium
A. Missing check if neighbor is already visited before recursive call
B. Visited array is not initialized
C. Incorrect loop condition syntax
D. Visited[node] should be set after recursion

Solution

  1. Step 1: Analyze DFS recursion calls

    The code calls dfs on all neighbors without checking if they are visited.
  2. Step 2: Identify risk of infinite recursion

    Without visited check, DFS may revisit nodes endlessly causing stack overflow.
  3. Final Answer:

    Missing check if neighbor is already visited before recursive call -> Option A
  4. Quick Check:

    Always check visited before recursion [OK]
Hint: Check visited before recursive DFS call to avoid loops [OK]
Common Mistakes:
  • Assuming visited check is optional
  • Setting visited after recursion
  • Ignoring infinite recursion risk
5. Given a directed graph with possible cycles, how can DFS be modified to detect if a cycle exists?
hard
A. Use a recursion stack array to track nodes in the current path and check if a node is revisited in this stack
B. Only mark nodes visited after all neighbors are processed
C. Use BFS instead of DFS to detect cycles
D. Ignore visited array and rely on node values

Solution

  1. Step 1: Understand cycle detection in DFS

    Detect cycles by tracking nodes currently in recursion (call) stack.
  2. 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.
  3. Step 3: Differentiate from visited array

    Visited marks all visited nodes; recursion stack tracks current path only.
  4. 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 A
  5. Quick Check:

    Recursion stack detects cycles in DFS [OK]
Hint: Track recursion stack to find cycles during DFS [OK]
Common Mistakes:
  • Confusing visited with recursion stack
  • Using BFS for cycle detection in directed graphs
  • Not tracking current path nodes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard