The whole, before the parts

Depth-first search explores one branch of a network as far as it can before returning to unfinished branches. Think of tracing passages through a maze while recording which places have already been visited. Citation needed

Terminology and core concepts

Depth-first search (DFS) explores a newly discovered neighbor before continuing with the current vertex’s remaining neighbors. Backtracking means returning to the previous unfinished vertex when a branch runs out. This iterative implementation keeps a stack of neighbor iterators, reproducing recursive DFS without relying on Python’s call stack. A visited set prevents cycles from causing repeated visits. The returned order depends on the order of neighbors. Citation needed

Learning path

Trace an example

edges: A -> B, C; B -> D; C -> D; D -> A
visit A       active path [A]
visit B       active path [A, B]
visit D       active path [A, B, D]   A already visited
backtrack     active path [A]
visit C       active path [A, C]      D already visited
finish        order [A, B, D, C]
The active path reaches D before returning to A’s second neighbor C.

Implement it in Python

Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed

def dfs(graph, start):
    seen = {start}
    order = [start]
    stack = [iter(graph.get(start, []))]
    while stack:
        neighbor = next(stack[-1], None)
        if neighbor is None:
            stack.pop()
        elif neighbor not in seen:
            seen.add(neighbor)
            order.append(neighbor)
            stack.append(iter(graph.get(neighbor, [])))
    return order

# Vertex names are strings; None is reserved for iterator exhaustion.
graph = {'A': ['B', 'C'], 'B': ['D'], 'C': ['D'], 'D': ['A']}
assert dfs(graph, 'A') == ['A', 'B', 'D', 'C']
assert dfs({}, 'A') == ['A']

Citation needed

Analyze the cost

Each reachable vertex is discovered once and each outgoing edge is considered once: O(V + E) time with expected constant-time set operations. The seen set, output, and iterator stack use O(V) extra space. Citation needed

A mistake to watch for

A visited neighbor alone does not prove a directed cycle: it may be in an already completed branch. Cycle detection needs to distinguish active vertices from completed ones. DFS also does not guarantee shortest paths. Citation needed

Practice and recall

  1. Why does the edge D to A not cause an infinite traversal?

    Work it out before opening the solution. Citation needed

    Show the reasoning
    1. A is marked seen before its neighbors are explored.
    2. When D encounters A, the membership check succeeds.
    3. No new stack entry is created for A, so the traversal can finish.

    Citation needed

Does the first DFS route to a vertex necessarily use the fewest edges?
No. Citation needed

To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed

Sources