Depth-First Search

Depth-First Search on Graphs

1. DFS: From Trees to Graphs Core idea recap: follow one path to the end The core idea of depth-first search (DFS) — explore a branch as deeply as possible, then backtrack when you hit a dead end — carries over to graphs unchanged. The new challenge: cycles Trees are acyclic. We move from a parent node to its children and never “walk back” to the parent. (For unrooted trees, this is avoided by passing the parent node as a parameter.) General graphs contain cycles. If we travel from u to v, v may well reach back to u along some other path. If this is not handled, DFS will fall into an infinite loop when it hits a cycle, causing a stack overflow. The solution: mark visited nodes We need an auxiliary data structure — typically a boolean array visited — to record which nodes have already been visited. Before visiting a new node, check whether it has been visited already.

Read note →

Depth-First Search and Backtracking

Introduction to DFS (Depth-First Search) What is a Search Algorithm? A search algorithm exhaustively explores part or all of the solution space of a problem to find its solution. Depth-First Search (DFS) Essence: DFS is essentially brute-force enumeration. “Depth-first” principle: Go as far down one path as possible; only backtrack when no further progress can be made. Example: Finding a Path from Node 1 to Node 8 Starting from node 1, always move to an unvisited node if one exists; otherwise, backtrack.

Read note →

Depth-First Search on Trees

What is Depth-First Search? Concept: Go All the Way Down One Path Depth-First Search (DFS) is an algorithm for traversing or searching trees or graphs. Its core idea is: starting from the root node, explore each branch as deeply as possible. When exploring along a path and all children of a node have been visited, the algorithm backtracks to that node’s parent and continues exploring any unvisited children. This process is typically implemented using recursion, which naturally uses the function call stack to handle the “going deeper” and “backtracking” phases. Traversal Order The order in which DFS visits nodes is closely tied to the order of recursive calls. It always completes the full exploration of one subtree before moving on to the next sibling subtree.

Read note →