CodeBlanks Logo Icon CodeBlanks

DFS idea

Follow a branch to the end before backtracking.

DFS idea

Depth-first search (DFS) follows a branch to the end, then backtracks at dead ends.

So DFS is naturally implemented with recursion or a stack; depth first is the priority.

DFS is often used for cycle detection, topological sort and pathfinding; its complexity is O(V + E).

Backtracking

Returning from a dead end to try another branch is called backtracking. This is core to DFS.

The state of returning branches is preserved; the path completes and no branch is skipped.

Thanks to backtracking, DFS safely visits every vertex even on cyclic graphs.

Practice DFS order

Write dfs_order(graph, start). Run stack-based DFS and return the visit order. Print [0, 2, 3, 1] with print(dfs_order({0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}, 0)).

Starter code

solution.py
def dfs_order(graph, start):
    # Stack-based DFS

Sample solution

solution.py
def dfs_order(graph, start):
    # Stack-based DFS
    visited = []
    stack = [start]
    while stack:
        node = stack.pop()
        if node not in visited:
            visited.append(node)
            for nb in reversed(graph[node]):
                if nb not in visited:
                    stack.append(nb)
    return visited
print(dfs_order({0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]}, 0))

Expected output

[0, 2, 3, 1]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which structure naturally implements DFS?

  • Stack or recursion Correct answer
  • Only a queue
  • Only a heap
  • Hash table

Explanation: Stack or recursion.

2 DFS start

Question
stack = [____]
Answer
stack = [start]

Explanation: start is right.

3 DFS idea: match the terms

Term Meaning
DFS Deep
stack LIFO
BFS Layer
recursion Self-call

All lessons in Intermediate