Depth-First Search (DFS) is an algorithm used to traverse graphs or tree structures by following one branch as deeply as possible before backtracking.
Starting from an initial node, DFS continues to an unvisited neighboring node until it reaches a dead end. It then moves back to the previous node and explores another branch.
Also known as: Depth-first traversal, DFS algorithm.
DFS can be implemented using recursion or a stack.
A basic DFS process works like this:
This approach allows DFS to explore deep paths efficiently.
Depth-First Search and Breadth-First Search are both graph traversal algorithms, but they explore nodes in different orders.
DFS can be useful for deep exploration, while BFS is often preferred when the goal is to find the shortest path in an unweighted graph.
DFS explores a path based on traversal order without estimating which route is most promising.
A Greedy Search uses a heuristic to choose the next node that appears closest to the goal.
In simple terms:
DFS can be used by web crawlers to explore a website by following links deeply before returning to other branches.
For example, a crawler may:
This traversal pattern can be useful when deeper pages are more important than broad site coverage.
Suppose a crawler starts at a website homepage with three category links.
Using DFS, it may first enter Category A, then follow a subcategory, then visit a product page, and continue deeper until no additional links remain.
Only after finishing that branch does the crawler return to the homepage and begin exploring Category B.
This differs from breadth-first traversal, which would normally visit all three category pages before moving deeper.
Depth-First Search is a graph traversal algorithm that explores one branch as deeply as possible before backtracking.
It is memory-efficient and useful for deep exploration, path discovery, and web crawling. However, it does not guarantee the shortest path and may spend time exploring long branches that are not relevant to the final goal.