Debth First
In our last post, we explored how BFS ripples out like a pebble in a pond. Today, we’re looking at its more adventurous cousin: Depth-First Search (DFS).
If BFS is a "layer-by-layer" explorer, DFS is a "dead-end" explorer.
What is DFS?
Imagine you are exploring a dark cave with multiple branching tunnels. Instead of checking the entrance of every tunnel first, you pick one path and walk as far as you can until you hit a wall. When you can't go any further, you backtrack to the last fork in the road and try the next path.
This "go deep before you go wide" approach is the heart of DFS.
The "Stack" Logic: LIFO
While BFS uses a Queue (First-In, First-Out), DFS uses a Stack (Last-In, First-Out).
Think of a stack of cafeteria trays. The last tray you put on top is the first one you take off. In DFS, the last "branch" you discover is the first one you explore to its very end.
A Quick JavaScript Example
Because DFS is about going deep and then coming back, it is often written using Recursion. Each function call "pauses" while the code dives deeper into the next node.
function dfs(graph, node, visited = new Set()) {
if (visited.has(node)) return;
console.log(`Exploring: ${node}`);
visited.add(node);
// Dive into each neighbor immediately
for (let neighbor of graph[node]) {
dfs(graph, neighbor, visited);
}
}
BFS vs. DFS: Which one to pick?
| Feature | BFS (Breadth-First) | DFS (Depth-First) |
|---|---|---|
| Data Structure | Queue (FIFO) | Stack (LIFO) or Recursion |
| Strength | Finding the Shortest Path | Exploring All Paths / Complexity |
| Memory | Uses more memory for "wide" graphs | Uses more memory for "deep" graph |
| Vibe | autious and organized | Bold and thorough |
When to use DFS?
Solving Mazes: DFS is natural for finding a way out of a labyrinth.
Task Scheduling: When one task must be done before another (Topological Sort).
Game AI: Checking all possible future moves in a game like Chess to see if a specific path leads to a win.
Comments
Post a Comment