Breadth First Search vs Depth First Search
Breadth First Search (BFS) and Depth First Search (DFS) are the two fundamental algorithms for traversing or searching tree and graph data structures. They differ in the order they visit nodes and the data structures they rely on internally.
Breadth First Search (BFS)
BFS explores all neighbors of a node before moving to the next level, using a queue to track nodes to visit. It finds the shortest path in terms of number of edges in unweighted graphs.
from collections import deque
def bfs(graph, start):
visited = {start}
queue = deque([start])
order = []
while queue:
node = queue.popleft()
order.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return order
Depth First Search (DFS)
DFS explores as far as possible along a branch before backtracking, using a stack (explicit or via recursion).
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
order = [start]
for neighbor in graph[start]:
if neighbor not in visited:
order.extend(dfs(graph, neighbor, visited))
return order
Comparison Table
| Aspect | BFS | DFS |
|---|---|---|
| Data structure | Queue | Stack / recursion |
| Memory usage | Higher (stores whole frontier) | Lower for deep/narrow graphs |
| Shortest path (unweighted) | Guaranteed | Not guaranteed |
| Use case | Shortest path, level-order traversal | Topological sort, cycle detection, connected components |
Complexity
| Metric | BFS | DFS |
|---|---|---|
| Time | O(V + E) | O(V + E) |
| Space | O(V) | O(V) |
PreviousDifference Between Stack and Queue Data Structure
Next Abstract Data Type in Data Structure with Example
Ready to master Data Structures & Algorithms?
Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.
.png)