Breadth-First Search (BFS) explores graph nodes level-by-level using a Queue. Depth-First Search (DFS) explores as deep as possible along each branch using a Stack or Recursion.
BFS is like ripples expanding outward in water (level by level). DFS is like a cave explorer walking down a tunnel to the bottom before backtracking.
~4,483 steps (Linearithmic)
O((V + E) log V) Time
O(V + E) Graph Memory
Memory growth rate as N expands.
Relative efficiency rating for large N.
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| BFS Time & Space | O(V + E) | O(V) |
| DFS Time & Space | O(V + E) | O(V) |
function bfs(graph, start) {
const visited = new Set([start]);
const queue = [start];
while (queue.length > 0) {
const node = queue.shift();
for (const neighbor of graph[node]) {
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}Finds 1st and 2nd degree friends.
Discovers URL links level by level.
Validate your conceptual understanding, operation mechanics, and core concepts of Bfs Dfs.
Use BFS for shortest paths in unweighted graphs. Use DFS for topological sorting, maze solving, and cycle detection!
Traverse tree network using BFS (Queue) or DFS (Stack) traversal rules.