Bird
Raised Fist0
DSA Pythonprogramming~3 mins

Why DFS Depth First Search on Graph in DSA Python?

Choose your learning style10 modes available
The Big Idea

What if you could explore every corner of a maze without ever getting lost or repeating steps?

The Scenario

Imagine you have a huge maze with many paths and rooms. You want to find a way to explore every room without missing any. If you try to remember every path manually, it becomes confusing and you might get lost or repeat rooms.

The Problem

Trying to explore the maze by guessing paths or writing down every step manually is slow and easy to mess up. You might forget where you came from or waste time going back and forth. It's hard to keep track of what you have already seen.

The Solution

Depth First Search (DFS) helps by exploring one path deeply before backtracking. It uses a simple rule: go as far as possible along one path, then back up when stuck. This way, you never lose track and visit every room exactly once.

Before vs After
✗ Before
visited = []
for node in graph:
    if node not in visited:
        # manually check neighbors and track visited
        pass
✓ After
def dfs(node, visited):
    visited.add(node)
    for neighbor in graph[node]:
        if neighbor not in visited:
            dfs(neighbor, visited)
What It Enables

DFS lets you explore complex networks or mazes completely and efficiently, making it easy to solve puzzles, find paths, or analyze connections.

Real Life Example

Think of a social network where you want to find all friends connected to a person. DFS helps you visit every friend and friend-of-friend without missing anyone.

Key Takeaways

Manual exploration is confusing and error-prone.

DFS explores deeply and backtracks to cover all nodes.

It helps solve problems involving paths and connections efficiently.

Practice

(1/5)
1. What does DFS (Depth First Search) do when exploring a graph?
easy
A. It explores as far as possible along each branch before backtracking.
B. It explores all neighbors at the current depth before going deeper.
C. It visits nodes randomly without any order.
D. It only visits nodes with the highest value first.

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 explores neighbors level by level, but DFS goes deep first.
  3. Final Answer:

    It explores as far as possible along each branch before backtracking. -> Option A
  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 randomly
  • Assuming DFS visits nodes by value
2. Which of the following is the correct Python syntax to start a DFS function on a graph represented as adjacency list graph from node start?
easy
A. def dfs(start, graph):
B. def dfs(graph, start):
C. def dfs(graph):
D. def dfs(start):

Solution

  1. Step 1: Identify required parameters for DFS

    DFS needs the graph and the starting node to begin traversal.
  2. Step 2: Check function signature correctness

    def dfs(graph, start): correctly defines a function with parameters (graph, start).
  3. Final Answer:

    def dfs(graph, start): -> Option B
  4. Quick Check:

    DFS needs graph and start node [OK]
Hint: DFS function needs graph and start node parameters [OK]
Common Mistakes:
  • Swapping parameter order incorrectly
  • Missing one of the parameters
  • Using only one parameter when two are needed
3. What is the output of the following DFS traversal starting from node 0?
graph = {0: [1, 2], 1: [2], 2: [0, 3], 3: [3]}
visited = set()
def dfs(node):
    if node not in visited:
        print(node, end=' ')
        visited.add(node)
        for neighbor in graph[node]:
            dfs(neighbor)
dfs(0)
medium
A. 0 3 2 1
B. 0 2 3 1
C. 0 1 3 2
D. 0 1 2 3

Solution

  1. Step 1: Start DFS from node 0

    Visit 0, mark visited. Neighbors: 1, 2.
  2. Step 2: Visit neighbor 1

    Visit 1, mark visited. Neighbor: 2.
  3. Step 3: Visit neighbor 2

    Visit 2, mark visited. Neighbors: 0 (visited), 3.
  4. Step 4: Visit neighbor 3

    Visit 3, mark visited. Neighbor: 3 (already visited).
  5. Final Answer:

    0 1 2 3 -> Option D
  6. Quick Check:

    DFS order = 0 1 2 3 [OK]
Hint: Follow neighbors depth-first, avoid revisiting nodes [OK]
Common Mistakes:
  • Visiting neighbors in wrong order
  • Revisiting already visited nodes
  • Confusing BFS order with DFS
4. Find the error in this DFS code snippet and select the fix:
graph = {0: [1], 1: [2], 2: []}
visited = set()
def dfs(node):
    if node in visited:
        return
    print(node)
    for neighbor in graph[node]:
        dfs(neighbor)
dfs(0)
medium
A. Add 'visited.add(node)' after printing node to mark it visited.
B. Change 'if node in visited' to 'if node not in visited'.
C. Remove the 'return' statement inside the if condition.
D. Add 'visited.remove(node)' after recursive calls.

Solution

  1. Step 1: Identify missing visited marking

    The code never adds nodes to visited, so it revisits nodes infinitely.
  2. Step 2: Fix by adding visited marking

    Adding 'visited.add(node)' after printing marks node as visited to avoid revisits.
  3. Final Answer:

    Add 'visited.add(node)' after printing node to mark it visited. -> Option A
  4. Quick Check:

    Mark visited after visiting node [OK]
Hint: Always add node to visited set after visiting [OK]
Common Mistakes:
  • Forgetting to mark nodes visited
  • Incorrect if condition logic
  • Removing nodes from visited incorrectly
5. Given a directed graph represented as adjacency list:
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1]}
Write the DFS traversal order starting from node 0 that detects cycles by tracking recursion stack. What is the order of nodes visited before detecting a cycle?
hard
A. 0 1 2
B. 0 2 3 1
C. 0 1 2 3
D. 0 2 1 3

Solution

  1. Step 1: Start DFS from node 0 and track recursion stack

    Visit 0, then 1, then 2, then 3. At 3, neighbor 1 is in recursion stack, cycle detected.
  2. Step 2: List nodes visited before cycle detection

    Nodes visited in order: 0, 1, 2, 3 before cycle found.
  3. Final Answer:

    0 1 2 3 -> Option C
  4. Quick Check:

    DFS with cycle detection visits 0 1 2 3 [OK]
Hint: Track recursion stack to detect cycles during DFS [OK]
Common Mistakes:
  • Ignoring recursion stack for cycle detection
  • Stopping traversal too early
  • Visiting nodes in wrong order
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