Take one path further.
Explore a graph with a stack and avoid cycling indefinitely.
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.
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.
PUSH the start
POP a candidate
IF unseen: mark visited and push neighbours
REPEAT03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
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"))['A', 'B', 'D', 'C']
- 1
The stack processes the newest candidate first. Reversing neighbour insertion preserves the fixture’s left-to-right visit preference.
- 2
A node may enter the stack more than once, but the seen check ensures its adjacency list is processed only once.
- 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
O(V + E) on adjacency lists
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
Use DFS to count how many vertices are reachable from A in a graph with an unreachable Z.
Reveal one possible solution +
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
Does DFS generally guarantee the shortest unweighted route?
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.