This guide explains Depth-First Search (DFS) from first principles. The goal is to understand the problem it solves, why the algorithm works, how to implement it, and where it appears in real software systems.
What problem does it solve?
Depth-First Search (DFS) belongs to the graph-algorithm toolbox. Before coding, define what the vertices represent, what an edge means, and what result the system actually needs.
The core idea in simple terms
مثل حل هزارتو است: یک مسیر را تا بنبست ادامه میدهیم و سپس برمیگردیم.
Step-by-step process
- رأس شروع را visited میکنیم.
- یک همسایه دیدهنشده را انتخاب میکنیم.
- در همان شاخه عمیق میشویم.
- در بنبست Backtrack میکنیم.
JavaScript example
function dfs(graph, start) {
const seen = new Set(), order = [];
function visit(u) {
if (seen.has(u)) return;
seen.add(u); order.push(u);
for (const v of graph[u] ?? []) visit(v);
}
visit(start); return order;
}Real-world and workplace examples
- پیمایش فایلها و پوشهها
- Cycle Detection
- Connected Components
- Backtracking و Maze
Time and space complexity
O(V + E) time و O(V) space
When should you use it?
Use it when the problem matches this condition: پیمایش عمیق، cycle و component.
When is it not a good fit?
It is usually not the best choice when: برای کوتاهترین مسیر بدون وزن، BFS مستقیمتر است..
Summary
Do not choose an algorithm by name alone. First identify whether the graph is directed or undirected, weighted or unweighted, and whether the goal is traversal, reachability, shortest path, connectivity, spanning structure, or combinatorial optimization.