Algorithms · Visualized
Depth-First Search
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
DFS dives as deep as possible along one branch before backtracking, using recursion (the call stack) or an explicit stack. Time: O(V + E) average, O(V + E) worst; space: O(V) recursion depth (a path graph makes the stack hold all V nodes).
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Depth-First Search (DFS)
Graph AlgorithmsDFS dives as deep as possible along one branch before backtracking, using recursion (the call stack) or an explicit stack. It does not compute shortest paths, but it is the backbone of almost every structural graph algorithm: cycle detection, topological sorting, connected components, bridges and articulation points all run a DFS and bookkeep what happens to each node and edge.
How Depth-First Search Works
- Mark the current node visited and record it in the visit order.
- Recurse into the first unvisited neighbour, going deeper before touching anything else.
- When a node has no unvisited neighbours, return — control backtracks to the caller.
- Backtracked edges are how DFS 'closes' a node; the recursion stack always holds the current root-to-node path.
- Loop over all nodes as possible start points so disconnected components are not missed.
Depth-First Search Worked Example
Input: {graph: A—B, A—C, B—C, B—D, C—D, C—E, D—E, D—F, E—F, start: A}
go(A) → mark A; neighbour B unvisited → go(B); B's neighbour C unvisited → go(C); C→D→E→F dive in a straight line; F has no new neighbours → return; each caller resumes, finds nothing new, and unwinds. Order: A B C D E F — same nodes, very different journey than BFS.
def dfs(graph, start):
visited = set()
order = []
def go(u):
visited.add(u)
order.append(u)
for v in graph[u]:
if v not in visited:
go(v) # dive deeper before backtracking
go(start)
return orderBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Depth-First Search Time & Space Complexity
When to Use Depth-First Search
- Foundation for cycle detection, topological sort, strongly connected components, bridges/articulation points.
- Flood fill, island counting, maze generation and solving, parsing nested structures.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.