When you're diving into Data Structures and Algorithms, graphs are one of the most exciting yet confusing concepts you'll face. But here's a trick once you understand BFS and DFS with solid examples, graphs stop being scary and start making sense.
In this blog, we’ll break down both BFS (Breadth-First Search) and DFS (Depth-First Search) using clear examples, C code, and real-world analogies. By the end, you’ll not just understand how to implement them you’ll know exactly when and why to use them.

Explore Uncodemy’s Data Structures Course interactive learning, real projects, and interview-ready concepts.
Imagine a network of cities connected by roads. Each city is a node (vertex), and the road connecting two cities is an edge. That’s a graph.
Now, how do you explore all the cities in a smart way? That’s where graph traversal comes into play.
The two most common algorithms to explore graphs:
Let’s break them down with real, working examples.
How BFS Works:
BFS starts from a node and explores all immediate neighbors first, before moving deeper into the graph.
It uses a Queue (FIFO) data structure.
Imagine spreading a rumor in a classroom. You tell your first-row friends. Then they tell their friends in the next row. The rumor spreads level by level that’s BFS!
BFS Algorithm (Steps):
1. Start from a source node.
2. Add it to the queue.
3. Mark it as visited.
4. While the queue is not empty:
BFS Example Graph:
0
/ \
1 2
| |
3 4
BFS C Code Example:
Copy Code
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int visited[SIZE] = {0};
int queue[SIZE], front = 0, rear = -1;
void enqueue(int value) {
queue[++rear] = value;
}
int dequeue() {
return queue[front++];
}
void bfs(int graph[SIZE][SIZE], int start) {
visited[start] = 1;
enqueue(start);
while (front <= rear) {
int current = dequeue();
printf("%d ", current);
for (int i = 0; i < SIZE; i++) {
if (graph[current][i] && !visited[i]) {
enqueue(i);
visited[i] = 1;
}
}
}
}
int main() {
int graph[SIZE][SIZE] = {
{0,1,1,0,0},
{1,0,0,1,0},
{1,0,0,0,1},
{0,1,0,0,0},
{0,0,1,0,0}
};
printf("BFS Traversal: ");
bfs(graph, 0);
return 0;
}Output:
BFS Traversal: 0 1 2 3 4
DFS (Depth-First Search) with Example
How DFS Works:
DFS starts from a node, explores as deep as possible along a branch, then backtracks.
It uses Stack (LIFO) or recursion.
Think of exploring a maze you go forward until you hit a wall, then backtrack and try a new path. That’s DFS!
DFS Algorithm (Steps):
1. Start from a source node.
2. Mark it as visited.
3. Explore each unvisited neighbor recursively.
4. Backtrack when needed.
DFS C Code Example:
Copy Code
#include <stdio.h>
#define SIZE 5
int visited[SIZE] = {0};
void dfs(int graph[SIZE][SIZE], int node) {
visited[node] = 1;
printf("%d ", node);
for (int i = 0; i < SIZE; i++) {
if (graph[node][i] && !visited[i]) {
dfs(graph, i);
}
}
}
int main() {
int graph[SIZE][SIZE] = {
{0,1,1,0,0},
{1,0,0,1,0},
{1,0,0,0,1},
{0,1,0,0,0},
{0,0,1,0,0}
};
printf("DFS Traversal: ");
dfs(graph, 0);
return 0;
}Output:
DFS Traversal: 0 1 3 2 4
| Feature | BFS | DFS |
| Structure | Queue | Stack/Recursion |
| Traversal | Level-wise | Depth-first |
| Path Finding | Finds shortest path | May not find shortest |
| Space | More (stores levels) | Less (unless deep tree) |
| Use Case | Social Networks, Maps | Puzzle solving, AI |
| Scenario | Algorithm to Use |
| Shortest path in unweighted graph | BFS |
| Maze or puzzle solver | DFS |
| Detecting cycles in a graph | DFS |
| Crawling search engine results | BFS |
| Topological sorting | DFS |
“How do you detect a cycle in a directed graph?”
Answer: Use DFS with recursion stack tracking.
“How to find shortest distance between two nodes?”
Answer: Use BFS it guarantees the shortest path in unweighted graphs.
Try solving problems on:
Q1. Which is better: BFS or DFS?
Depends on the problem. Use BFS for shortest paths; use DFS for exploring all paths.
Q2. Can DFS be implemented iteratively?
Yes, using a stack instead of recursion.
Q3. Does DFS or BFS use more memory?
BFS usually uses more memory because it stores all neighbors at each level.
Q4. Are BFS and DFS only for graphs?
Nope. Trees, grids, mazes anything with nodes and connections.
Q5. Can BFS and DFS fail?
They can loop infinitely if you forget to mark nodes as visited. Always handle that.
Whether you’re prepping for a coding interview or just trying to level up your DSA game, understanding BFS and DFS with actual examples is essential. They’re more than just theory they’re part of your problem-solving toolbox.
Personalized learning paths with interactive materials and progress tracking for optimal learning experience.
Explore LMSCreate professional, ATS-optimized resumes tailored for tech roles with intelligent suggestions.
Build ResumeDetailed analysis of how your resume performs in Applicant Tracking Systems with actionable insights.
Check ResumeAI analyzes your code for efficiency, best practices, and bugs with instant feedback.
Try Code ReviewPractice coding in 20+ languages with our cloud-based compiler that works on any device.
Start Coding
TRENDING
BESTSELLER
BESTSELLER
TRENDING
HOT
BESTSELLER
HOT
BESTSELLER
BESTSELLER
HOT
POPULAR