Bird
Raised Fist0
DSA Cprogramming~30 mins

DFS Depth First Search on Graph in DSA C - Build from Scratch

Choose your learning style10 modes available
DFS Depth First Search on Graph
📖 Scenario: You are working with a simple map of connected cities. Each city is connected to some other cities by roads. You want to explore all cities reachable from a starting city using Depth First Search (DFS).
🎯 Goal: Build a program that uses DFS to visit all cities connected to a starting city and prints the order of visiting.
📋 What You'll Learn
Create an adjacency list to represent the graph of cities
Create a visited array to track visited cities
Implement DFS using recursion
Print the order of cities visited by DFS
💡 Why This Matters
🌍 Real World
DFS is used in many real-world problems like finding connected components, solving puzzles, and exploring networks.
💼 Career
Understanding DFS is essential for software engineers working on graph algorithms, network analysis, and problem-solving.
Progress0 / 4 steps
1
Create the graph adjacency list
Create an integer 2D array called graph with 4 rows and 4 columns representing the adjacency matrix of the graph. Initialize it with these exact values: row 0: {0, 1, 1, 0}, row 1: {1, 0, 0, 1}, row 2: {1, 0, 0, 1}, row 3: {0, 1, 1, 0}.
DSA C
Hint

Use a 2D array with 4 rows and 4 columns. Each row is an array of 4 integers.

2
Create the visited array
Create an integer array called visited of size 4 and initialize all elements to 0.
DSA C
Hint

Use an integer array of size 4 and initialize all elements to zero.

3
Implement the DFS function
Write a recursive function called dfs that takes an integer node as input. Inside the function, mark visited[node] as 1. Then use a for loop with variable i from 0 to 3 to check if graph[node][i] is 1 and visited[i] is 0. If yes, call dfs(i) recursively.
DSA C
Hint

Mark the node visited, then loop over all nodes to find connected unvisited nodes and call dfs recursively.

4
Print the DFS visiting order
In the main function, call dfs(0) to start DFS from node 0. Then use a for loop with variable i from 0 to 3 to print i if visited[i] is 1. Print all visited nodes separated by spaces on one line.
DSA C
Hint

After DFS, print all nodes where visited[i] is 1 separated by spaces.

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