Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Graphs and connections
EXPERIMENT 38 / 66

Take one path further.

Explore a graph with a stack and avoid cycling indefinitely.

BY NAVAN SAMI◷ 8 MIN READCOREALGORITHM

01 Model 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.

THE THING THAT MUST STAY TRUE

Each vertex’s adjacency list is processed only on its first visit.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
PUSH the start
POP a candidate
IF unseen: mark visited and push neighbours
REPEAT

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

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']
  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 Count the cost

TIME

O(V + E) on adjacency lists

SPACE

O(V + E) worst-case explicit pending entries in this version

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

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))

06 Check your reasoning

QUICK SIGNAL CHECK

Does DFS generally guarantee the shortest unweighted route?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.