BFS and DFS show up in every technical
interview. Most developers know the
names but get confused explaining
the difference.
Until you see them run on the same graph.
The Core Difference
BFS (Breadth First Search) uses a Queue.
\javascript
// BFS — process level by level
const queue = [startNode];
while (queue.length > 0) {
const node = queue.shift(); // front
visited.add(node);
for (const neighbor of adj[node]) {
if (!visited.has(neighbor)) {
queue.push(neighbor); // back
}
}
}
\\
DFS (Depth First Search) uses a Stack
(or recursion).
\javascript
// DFS — go deep first
function dfs(node) {
visited.add(node);
for (const neighbor of adj[node]) {
if (!visited.has(neighbor)) {
dfs(neighbor); // recurse deep
}
}
}
\\
When to Use Each
BFS → Shortest path, level-order traversal,
GPS navigation, social network degrees
DFS → Cycle detection, topological sort,
maze solving, all possible paths
Watch It
What's Next
Dijkstra's Algorithm — shortest path in
weighted graphs. The algorithm powering
GPS navigation.
Subscribe to AlgoCanvas:
👉 youtube.com/@AlgoCanvas
Top comments (0)