Bird
Raised Fist0
DSA Goprogramming~10 mins

DFS Depth First Search on Graph in DSA Go - Execution Trace

Choose your learning style10 modes available
Concept Flow - DFS Depth First Search on Graph
Start at chosen node
↓
Mark node as visited
↓
For each neighbor
↓
If neighbor not visited?
No→Skip
Yes↓
Recursively DFS on neighbor
↓
All neighbors visited?
↓
Backtrack to previous node
↓
Done when all reachable nodes visited
Start from a node, visit it, then recursively visit each unvisited neighbor, backtracking when no new neighbors remain.
Execution Sample
DSA Go
func DFS(node string, graph map[string][]string, visited map[string]bool) {
    visited[node] = true
    for _, neighbor := range graph[node] {
        if !visited[neighbor] {
            DFS(neighbor, graph, visited)
        }
    }
}
This code visits nodes in depth-first order, marking each visited and recursively exploring neighbors.
Execution Table
StepOperationCurrent NodeVisited SetStack (Call Trace)ActionGraph State
1Start DFSA{}[A]Mark A visitedGraph unchanged
2Explore neighbors of AA{A}[A]Check BGraph unchanged
3DFS call on BB{A}[A, B]Mark B visitedGraph unchanged
4Explore neighbors of BB{A, B}[A, B]Check CGraph unchanged
5DFS call on CC{A, B}[A, B, C]Mark C visitedGraph unchanged
6Explore neighbors of CC{A, B, C}[A, B, C]Check DGraph unchanged
7DFS call on DD{A, B, C}[A, B, C, D]Mark D visitedGraph unchanged
8Explore neighbors of DD{A, B, C, D}[A, B, C, D]Check BGraph unchanged
9Neighbor B already visitedD{A, B, C, D}[A, B, C, D]Skip BGraph unchanged
10All neighbors of D visitedD{A, B, C, D}[A, B, C, D]BacktrackGraph unchanged
11Back to CC{A, B, C, D}[A, B, C]Check EGraph unchanged
12DFS call on EE{A, B, C, D}[A, B, C, E]Mark E visitedGraph unchanged
13Explore neighbors of EE{A, B, C, D, E}[A, B, C, E]Check FGraph unchanged
14DFS call on FF{A, B, C, D, E}[A, B, C, E, F]Mark F visitedGraph unchanged
15Explore neighbors of FF{A, B, C, D, E, F}[A, B, C, E, F]Check CGraph unchanged
16Neighbor C already visitedF{A, B, C, D, E, F}[A, B, C, E, F]Skip CGraph unchanged
17All neighbors of F visitedF{A, B, C, D, E, F}[A, B, C, E, F]BacktrackGraph unchanged
18Back to EE{A, B, C, D, E, F}[A, B, C, E]All neighbors visitedGraph unchanged
19Back to CC{A, B, C, D, E, F}[A, B, C]All neighbors visitedGraph unchanged
20Back to BB{A, B, C, D, E, F}[A, B]All neighbors visitedGraph unchanged
21Back to AA{A, B, C, D, E, F}[A]Check CGraph unchanged
22Neighbor C already visitedA{A, B, C, D, E, F}[A]Skip CGraph unchanged
23All neighbors of A visitedA{A, B, C, D, E, F}[]DFS completeGraph unchanged
💡 All reachable nodes visited, recursion unwound fully
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5After Step 7After Step 12After Step 14After Step 23
Current NodeNoneABCDEFNone
Visited Set{}{A}{A, B}{A, B, C}{A, B, C, D}{A, B, C, D, E}{A, B, C, D, E, F}{A, B, C, D, E, F}
Stack (Call Trace)[][A][A, B][A, B, C][A, B, C, D][A, B, C, E][A, B, C, E, F][]
Key Moments - 3 Insights
Why do we skip neighbors that are already visited instead of visiting them again?
Because revisiting nodes would cause infinite loops. The execution_table rows 8 and 15 show skipping neighbors already in the visited set to prevent repeated visits.
Why does the stack (call trace) grow and shrink during DFS?
The stack grows when we go deeper into neighbors (recursive calls) and shrinks when we backtrack after visiting all neighbors. See rows 3 to 10 for stack growth and rows 10 to 23 for shrinking.
What does backtracking mean in DFS?
Backtracking means returning to the previous node after all neighbors are visited. This is shown in rows 10, 17, 18, and onwards where the stack shrinks and the current node moves back.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 7, which nodes are visited?
A{A, B, C}
B{A, B}
C{A, B, C, D}
D{A}
💡 Hint
Check the 'Visited Set' column at Step 7 in the execution_table.
At which step does the DFS first backtrack from node D?
AStep 10
BStep 9
CStep 11
DStep 8
💡 Hint
Look for 'Backtrack' action in the execution_table after visiting D.
If node E had no neighbors, how would the stack change at Step 12?
AStack would remain [A, B, C, E]
BStack would immediately shrink after Step 12
CStack would grow larger than [A, B, C, E]
DStack would be empty
💡 Hint
Consider that no neighbors means no further recursive calls, so backtracking happens immediately.
Concept Snapshot
DFS (Depth First Search) explores graph nodes by going deep along neighbors before backtracking.
Start at a node, mark visited, recursively visit unvisited neighbors.
Uses recursion stack to track path.
Prevents cycles by skipping visited nodes.
Backtracking occurs when no unvisited neighbors remain.
Useful for exploring all reachable nodes deeply.
Full Transcript
DFS Depth First Search starts at a chosen node, marks it visited, then explores each neighbor recursively if not visited. The recursion stack grows as we go deeper and shrinks when backtracking. Visited nodes are tracked to avoid cycles. The process ends when all reachable nodes are visited and recursion unwinds fully. This trace shows step-by-step how nodes are visited, neighbors checked, and backtracking happens, with the stack and visited set changing accordingly.

Practice

(1/5)
1. What is the main idea behind Depth First Search (DFS) on a graph?
easy
A. Visit nodes in order of their distance from the start node
B. Visit all neighbors of a node before moving deeper
C. Explore as far as possible along each branch before backtracking
D. Randomly visit nodes without any order

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 options with DFS behavior

    Explore as far as possible along each branch before backtracking matches this behavior exactly, while others describe BFS or incorrect methods.
  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 neighbors first
  • Assuming DFS visits nodes by distance
2. Which of the following is the correct way to start a DFS function in Go for a graph represented as adjacency list graph map[int][]int?
easy
A. func dfs(node int, visited map[int]bool) {}
B. func dfs(node int, visited []int) {}
C. func dfs(node int, visited map[int]int) {}
D. func dfs(node int, visited []bool) {}

Solution

  1. Step 1: Identify correct visited type for DFS

    Visited should be a map[int]bool to mark nodes visited or not.
  2. Step 2: Check options for visited parameter type

    Only func dfs(node int, visited map[int]bool) {} uses map[int]bool, others use incorrect types.
  3. Final Answer:

    func dfs(node int, visited map[int]bool) {} -> Option A
  4. Quick Check:

    Visited map with bool = correct DFS parameter [OK]
Hint: Use map[int]bool to track visited nodes in Go DFS [OK]
Common Mistakes:
  • Using slice instead of map for visited
  • Using wrong map value type
  • Ignoring visited parameter
3. What is the output of the following Go code snippet using DFS on the graph?
graph := map[int][]int{
  1: {2, 3},
  2: {4},
  3: {},
  4: {},
}
visited := map[int]bool{}
var result []int
var dfs func(int)
dfs = func(node int) {
  if visited[node] {
    return
  }
  visited[node] = true
  result = append(result, node)
  for _, n := range graph[node] {
    dfs(n)
  }
}
dfs(1)
fmt.Println(result)
medium
A. [1 2 4 3]
B. [1 3 2 4]
C. [1 2 3 4]
D. [1 4 2 3]

Solution

  1. Step 1: Trace DFS starting at node 1

    Visit 1, then go to 2, then 4 (no children), backtrack, then visit 3.
  2. Step 2: Record order of visited nodes

    Order is 1, 2, 4, 3 as DFS explores deep before backtracking.
  3. Final Answer:

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

    DFS order = [1 2 4 3] [OK]
Hint: Follow each branch fully before moving to next neighbor [OK]
Common Mistakes:
  • Visiting neighbors in wrong order
  • Confusing BFS order with DFS
  • Not marking visited nodes
4. The following DFS code in Go has a bug. What is the error?
func dfs(node int, graph map[int][]int, visited map[int]bool) {
  if visited[node] {
    return
  }
  visited[node] = true
  for _, n := range graph[node] {
    dfs(n, graph, visited)
  }
}

// Called as dfs(1, graph, visited)
medium
A. Missing base case to stop recursion
B. Visited map is not updated correctly
C. Incorrect parameter types in function
D. No code to process or print the node

Solution

  1. Step 1: Analyze DFS function behavior

    Function marks visited and recurses but does not process or print nodes.
  2. Step 2: Identify missing action

    DFS usually processes nodes (e.g., print or collect), missing here causes no visible output.
  3. Final Answer:

    No code to process or print the node -> Option D
  4. Quick Check:

    DFS missing node processing step [OK]
Hint: DFS must process nodes inside function [OK]
Common Mistakes:
  • Assuming marking visited is enough
  • Forgetting to print or collect nodes
  • Thinking recursion stops without base case
5. Given a graph with possible cycles, how can you modify DFS in Go to detect if a cycle exists?
hard
A. Only mark nodes visited after all neighbors are processed
B. Use a recursion stack map to track nodes currently in the call stack
C. Use BFS instead of DFS to detect cycles
D. Ignore visited nodes and traverse all edges

Solution

  1. Step 1: Understand cycle detection in DFS

    Detect cycles by tracking nodes currently in recursion stack to find back edges.
  2. Step 2: Choose correct method

    Using a recursion stack map helps detect if a node is revisited while still in the current path.
  3. Final Answer:

    Use a recursion stack map to track nodes currently in the call stack -> Option B
  4. Quick Check:

    Cycle detection = recursion stack tracking [OK]
Hint: Track recursion stack to find cycles in DFS [OK]
Common Mistakes:
  • Marking visited too late
  • Using BFS which doesn't detect cycles easily
  • Ignoring visited nodes causing infinite loops
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