Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Think in algorithms
EXPERIMENT 77 / 101

Take one path further.

Explore a graph with a stack and avoid cycling indefinitely.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

Depth-first search explores down one branch before returning to other candidates. An explicit stack avoids Python recursion depth for a long path. A visited set prevents infinite revisits in a cyclic graph. DFS is useful for reachability, connected components, and as a component of other algorithms, but it does not generally return a shortest unweighted path.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

depth_first_search.py
def dfs(graph, start):
    stack, seen, order = [start], set(), []
    while stack:
        node = stack.pop()
        if node in seen: continue
        seen.add(node); order.append(node)
        stack.extend(reversed(graph.get(node, [])))
    return order
graph = {"A": ["B", "C"], "B": ["D"], "C": [], "D": ["A"]}
print(dfs(graph, "A"))
↳ EXPECTED OUTPUT
['A', 'B', 'D', 'C']

03 Under the hood

  1. 1

    The stack processes the newest candidate first. Reversing neighbour insertion preserves the fixture’s left-to-right visit preference.

  2. 2

    A node may enter the stack more than once, but the seen check ensures its adjacency list is processed only once.

  3. 3

    For adjacency lists, traversal is O(V + E) over the reachable region. In a directed graph, reachability from one start does not imply reverse reachability or membership in one strongly connected component.

04 Your turn, builder

A SMALL MISSION

Use DFS to count how many vertices are reachable from A in a graph with an unreachable Z.

Reveal one possible solution +
one_possible_solution.py
graph = {"A": ["B"], "B": [], "Z": []}
stack, seen = ["A"], set()
while stack:
    node = stack.pop()
    if node not in seen:
        seen.add(node); stack.extend(graph[node])
print(len(seen))

05 Check your signal

QUICK SIGNAL CHECK

Does DFS generally guarantee the shortest unweighted route?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.