Bird
Raised Fist0
DSA Cprogramming~10 mins

Topological Sort Using DFS in DSA C - Execution Trace

Choose your learning style10 modes available
Concept Flow - Topological Sort Using DFS
Start DFS at unvisited node
↓
Mark node as visited
↓
For each neighbor
↓
If neighbor unvisited
↓
Recursive DFS on neighbor
↓
After all neighbors visited
↓
Push node to stack
↓
Repeat for all nodes
↓
Pop all nodes from stack for topological order
Start DFS from each unvisited node, visit all neighbors recursively, then push the node to a stack. Finally, pop nodes from the stack to get topological order.
Execution Sample
DSA C
void dfs(int node) {
  visited[node] = true;
  for (int neighbor : graph[node]) {
    if (!visited[neighbor]) dfs(neighbor);
  }
  stack.push(node);
}
This code visits nodes recursively and pushes them to a stack after visiting all neighbors.
Execution Table
StepOperationCurrent NodeVisited SetStack StateVisual State
1Start DFS at node 55{}[]Graph nodes: 5,4,3,2,1,0; No nodes visited
2Visit node 55{5}[]Visited 5
3Check neighbors of 5: 2,05{5}[]Neighbors 2 and 0 unvisited
4DFS on neighbor 22{5}[]Move to node 2
5Visit node 22{2,5}[]Visited 2
6Check neighbors of 2: 32{2,5}[]Neighbor 3 unvisited
7DFS on neighbor 33{2,5}[]Move to node 3
8Visit node 33{2,3,5}[]Visited 3
9Check neighbors of 3: 13{2,3,5}[]Neighbor 1 unvisited
10DFS on neighbor 11{2,3,5}[]Move to node 1
11Visit node 11{1,2,3,5}[]Visited 1
12Check neighbors of 1: none1{1,2,3,5}[]No neighbors
13Push node 1 to stack1{1,2,3,5}[1]Stack: 1
14Return to node 33{1,2,3,5}[1]Back to 3
15Push node 3 to stack3{1,2,3,5}[1,3]Stack: 1 -> 3
16Return to node 22{1,2,3,5}[1,3]Back to 2
17Push node 2 to stack2{1,2,3,5}[1,3,2]Stack: 1 -> 3 -> 2
18Return to node 55{1,2,3,5}[1,3,2]Back to 5
19Check neighbor 0 of 55{1,2,3,5}[1,3,2]Neighbor 0 unvisited
20DFS on neighbor 00{1,2,3,5}[1,3,2]Move to node 0
21Visit node 00{0,1,2,3,5}[1,3,2]Visited 0
22Check neighbors of 0: none0{0,1,2,3,5}[1,3,2]No neighbors
23Push node 0 to stack0{0,1,2,3,5}[1,3,2,0]Stack: 1 -> 3 -> 2 -> 0
24Return to node 55{0,1,2,3,5}[1,3,2,0]Back to 5
25Push node 5 to stack5{0,1,2,3,5}[1,3,2,0,5]Stack: 1 -> 3 -> 2 -> 0 -> 5
26Start DFS at node 44{0,1,2,3,5}[1,3,2,0,5]Node 4 unvisited
27Visit node 44{0,1,2,3,4,5}[1,3,2,0,5]Visited 4
28Check neighbors of 4: 14{0,1,2,3,4,5}[1,3,2,0,5]Neighbor 1 visited
29Push node 4 to stack4{0,1,2,3,4,5}[1,3,2,0,5,4]Stack: 1 -> 3 -> 2 -> 0 -> 5 -> 4
30All nodes visited-{0,1,2,3,4,5}[1,3,2,0,5,4]DFS complete
31Pop all nodes from stack---Topological order: 4 -> 5 -> 0 -> 2 -> 3 -> 1
💡 All nodes visited and pushed to stack; popping stack gives topological order
Variable Tracker
VariableStartAfter Step 2After Step 5After Step 8After Step 11After Step 13After Step 15After Step 17After Step 23After Step 25After Step 29Final
visited{}{5}{2,5}{2,3,5}{1,2,3,5}{1,2,3,5}{1,2,3,5}{1,2,3,5}{0,1,2,3,5}{0,1,2,3,5}{0,1,2,3,4,5}{0,1,2,3,4,5}
stack[][][][][][1][1,3][1,3,2][1,3,2,0][1,3,2,0,5][1,3,2,0,5,4][1,3,2,0,5,4]
Key Moments - 3 Insights
Why do we push the node to the stack only after visiting all its neighbors?
Because in the execution_table rows 12-13 and 22-23, nodes are pushed after all neighbors are visited, ensuring dependencies come before the node in the topological order.
What happens if a node has no neighbors?
As shown in rows 12 and 22, if a node has no neighbors, it is pushed immediately to the stack, since there are no dependencies to wait for.
Why do we start DFS from unvisited nodes only?
Because in row 26, DFS starts only at node 4 which was unvisited; visited nodes are skipped to avoid repeated work and infinite loops.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 13, what is the stack state?
A[1]
B[3]
C[1,3]
D[]
💡 Hint
Check the 'Stack State' column at step 13 in execution_table
At which step does the node 0 get pushed to the stack?
AStep 20
BStep 23
CStep 22
DStep 25
💡 Hint
Look for 'Push node 0 to stack' operation in execution_table
If node 4 had a neighbor 5 (already visited), what would happen at step 28?
ANode 5 would be removed from visited set
BNode 4 would be pushed to stack immediately
CDFS would skip neighbor 5 and continue
DDFS would recurse on 5 again
💡 Hint
Refer to step 28 where neighbor 1 is visited and DFS does not recurse again
Concept Snapshot
Topological Sort Using DFS:
- Visit each unvisited node with DFS
- Recursively visit all neighbors first
- Push node to stack after neighbors
- Pop stack for topological order
- Ensures dependencies come before dependents
Full Transcript
Topological Sort using DFS works by visiting each node that has not been visited yet. For each node, we mark it visited and recursively visit all its neighbors. After all neighbors are visited, we push the current node to a stack. This ensures that nodes are pushed only after their dependencies. Finally, popping all nodes from the stack gives the topological order. The execution table shows step-by-step how nodes are visited, neighbors checked, and nodes pushed to the stack. The variable tracker shows how the visited set and stack change over time. Key moments clarify why nodes are pushed after neighbors and why DFS starts only at unvisited nodes. The visual quiz tests understanding of stack states and DFS behavior.

Practice

(1/5)
1. What is the main purpose of using DFS in Topological Sort on a Directed Acyclic Graph (DAG)?
easy
A. To visit nodes in a way that all dependencies come before the node
B. To find the shortest path between two nodes
C. To detect cycles in an undirected graph
D. To count the number of connected components

Solution

  1. Step 1: Understand DFS role in Topological Sort

    DFS visits nodes deeply, ensuring all nodes reachable from a node are visited before the node itself.
  2. Step 2: Relate DFS to dependency order

    This ensures nodes appear after all their dependencies, which is the goal of topological sorting.
  3. Final Answer:

    To visit nodes in a way that all dependencies come before the node -> Option A
  4. Quick Check:

    DFS orders nodes respecting dependencies [OK]
Hint: DFS ensures dependencies come before nodes in topological order [OK]
Common Mistakes:
  • Confusing topological sort with shortest path
  • Thinking DFS detects cycles in undirected graphs here
  • Mixing connected components with topological order
2. Which of the following is the correct way to mark a node as visited in a DFS-based topological sort in C?
easy
A. visited(node) = true;
B. visited[node] = 1;
C. visited[node] == true;
D. visited[node] = false;

Solution

  1. Step 1: Understand C syntax for arrays

    In C, arrays use square brackets to access elements, so visited[node] is correct.
  2. Step 2: Assigning visited status

    Assigning 1 marks the node as visited; '==' is comparison, not assignment; 'false' would mark unvisited.
  3. Final Answer:

    visited[node] = 1; -> Option B
  4. Quick Check:

    Use visited[node] = 1 to mark visited [OK]
Hint: Use visited[node] = 1 to mark visited in C arrays [OK]
Common Mistakes:
  • Using parentheses instead of brackets for arrays
  • Using '==' instead of '=' for assignment
  • Assigning false instead of true/1 to mark visited
3. What is the output order of nodes after performing DFS-based topological sort on this graph?
Edges:
0 -> 1
0 -> 2
1 -> 3
2 -> 3
Assume nodes are pushed to stack after visiting all neighbors and stack is printed top to bottom.
medium
A. [0, 2, 1, 3]
B. [3, 2, 1, 0]
C. [0, 1, 2, 3]
D. [3, 1, 2, 0]

Solution

  1. Step 1: Perform DFS starting from node 0

    Visit 0, then neighbors 1 then 2 (edge order). From 1 to 3, from 2 to 3 (visited).
  2. Step 2: Push nodes to stack after visiting neighbors

    Push 3, then 1, then 3 already visited, then 2, then 0. Stack top to bottom: [3, 1, 2, 0].
  3. Final Answer:

    [3, 1, 2, 0] -> Option D
  4. Quick Check:

    Stack top to bottom after DFS = [3, 1, 2, 0] [OK]
Hint: Push nodes after neighbors; output is stack top to bottom [OK]
Common Mistakes:
  • Pushing nodes before visiting neighbors
  • Confusing order of neighbors visited
  • Printing stack bottom to top instead of top to bottom
4. Identify the error in this DFS-based topological sort code snippet in C:
void dfs(int node) {
  visited[node] = 1;
  for (int i = 0; i < adj[node].size(); i++) {
    int nbr = adj[node][i];
    if (!visited[nbr])
      dfs(nbr);
  }
  stack.push(node);
}
medium
A. Stack push should be before recursive calls
B. Missing base case for cycle detection
C. Using adj[node].size() is invalid in C
D. visited array should be initialized to 2 instead of 1

Solution

  1. Step 1: Check syntax for adjacency list size in C

    adj[node].size() is C++ syntax; C does not support .size() method on arrays.
  2. Step 2: Identify correct way to get adjacency list size in C

    In C, adjacency lists are usually arrays with separate size variables; .size() causes compile error.
  3. Final Answer:

    Using adj[node].size() is invalid in C -> Option C
  4. Quick Check:

    adj[node].size() is C++ only, not C [OK]
Hint: Use array length variables in C, not .size() method [OK]
Common Mistakes:
  • Confusing C and C++ syntax for containers
  • Ignoring cycle detection in topological sort
  • Pushing nodes before recursive calls
5. Given a graph with edges:
5 -> 2
5 -> 0
4 -> 0
4 -> 1
2 -> 3
3 -> 1
Which of the following is a valid topological order using DFS-based topological sort?
hard
A. [4, 5, 2, 3, 1, 0]
B. [4, 0, 5, 2, 3, 1]
C. [5, 0, 4, 2, 3, 1]
D. [5, 4, 3, 2, 1, 0]

Solution

  1. Step 1: Analyze prerequisites from edges

    (u -> v means u before v): 5 before 2 and 0; 4 before 0 and 1; 2 before 3; 3 before 1.
  2. Step 2: Check each option for prerequisite order

    [4, 5, 2, 3, 1, 0]: 4 before 0 and 1, 5 before 2 and 0, 2 before 3, 3 before 1, all correct.
  3. Final Answer:

    [4, 5, 2, 3, 1, 0] -> Option A
  4. Quick Check:

    All edges respected in order D [OK]
Hint: Check each edge u->v: u appears before v in order [OK]
Common Mistakes:
  • Ignoring edge directions in order
  • Placing dependent nodes before their prerequisites
  • Assuming any order with all nodes is valid
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