Introduction
BFS (Breadth-First Search) and DFS (Depth-First Search) are two fundamental graph traversal algorithms in Data Structures and Algorithms (DSA). These algorithms are extremely important because almost every graph problem is based on either BFS, DFS, or a combination of both.
In simple terms, graph traversal means visiting all the nodes (vertices) of a graph systematically.
What is a Graph?
A Graph is a data structure made of:
Vertices (nodes) – points in the graph
Edges – connections between nodes
Graphs can represent:
Social networks
Road maps
Computer networks
Dependency systems
Graphs can be directed or undirected, and weighted or unweighted.
What is Graph Traversal?
Graph traversal is the process of visiting every node of the graph exactly once (if possible).
Traversal is required for:
Searching a node
Finding connected components
Detecting cycles
Shortest path problems
The two most commonly used traversal techniques are BFS and DFS.
What is BFS (Breadth First Search)?
Breadth First Search (BFS) explores the graph level by level.
In BFS:
We first visit all neighbors of a node
Then move to the next level of neighbors
BFS uses a Queue data structure.
BFS Real-Life Analogy
Think of spreading news:
First, you tell your close friends
Then your friends tell their friends
This level-by-level spreading is similar to BFS.
BFS Example Graph
Consider this graph:
0
/ \
1 2
| |
3 4
Starting node: 0
BFS Traversal Order
0 → 1 → 2 → 3 → 4
BFS Step-by-Step Explanation
Steps:
Create a queue
Mark the starting node as visited
Push it into the queue
While queue is not empty:
Remove front node
Visit it
Add all unvisited neighbors to the queue
BFS Dry Run
| Queue | Visited | Output |
|---|---|---|
| [0] | 0 | 0 |
| [1,2] | 0,1,2 | 0 |
| [2,3] | 0,1,2,3 | 0,1 |
| [3,4] | 0,1,2,3,4 | 0,1,2 |
BFS Code Implementation
C++ Code
void bfs(int start, vector<vector<int>>& graph) {
vector<bool> visited(graph.size(), false);
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
}
}
}
}
Join the conversation! Your thoughts help the community grow.