DFS

Also known as: Depth-first search, Depth first search

DFS (depth-first search) explores a graph by going as deep as possible along each branch before backtracking. Implement with an explicit stack or with recursion (the call stack).

Time $O(V + E)$ with adjacency lists. Discovery and finish times support cycle detection, topological sort on DAGs, and strongly connected components (Kosaraju / Tarjan).

Prefer DFS when you care about path existence, structure (cycles, SCC), or backtracking search. Prefer BFS when you need fewest edges from a source.

← Back to CS Glossary