Depth-first and breadth-first search
Explore a graph level by level with a queue (BFS) or go as deep as possible with a stack or recursion (DFS).
Syllabus says: “Depth First Search and Breadth First Search”
On this page · 12 sections
BFS = Queue = ripples spreading in a pond (level by level). DFS = Stack = exploring a cave: go deep, BACKTRACK when stuck.
Spreading exam news: BFS is you telling all your friends first, then they tell theirs. DFS is one friend who tells one person, who tells one person… and only comes back when the chain ends.
BFS visits a start vertex, then all its unvisited neighbours, then their neighbours, using a queue; DFS visits a vertex and recursively visits its first unvisited neighbour, backtracking when none remain. Both take O(n + e) with adjacency lists.
BFS: ഓളം പോലെ പരക്കും. DFS: ഗുഹയിൽ ആഴത്തിൽ പോയി തിരിച്ചു വരും.
What you will be able to do
- Write Breadth First Search, BFS (Nov 2025 Q14a) and Depth First Search, DFS (May 2026 Q14a).
- Trace both with ascending-order tie-breaking, as KTU asks.
- State their complexity.
Uses
- BFS: shortest path in unweighted graphs, nearest friends, web crawling.
- DFS: detecting cycles, topological order, maze solving, connected components.
Worked example
Graph: 0–1, 0–2, 1–2, 1–3, 2–4, 3–4 (the same graph as in the representation lesson). Start at 0; neighbours are taken in ascending order.
| Dequeue | Enqueue (new) | Queue after | Visited order |
|---|---|---|---|
| 0 | 1, 2 | 1 2 | 0 |
| 1 | 3 (0, 2 already seen) | 2 3 | 0 1 |
| 2 | 4 | 3 4 | 0 1 2 |
| 3 | — | 4 | 0 1 2 3 |
| 4 | — | empty | 0 1 2 3 4 |
| Call | Action | Stack (recursion) |
|---|---|---|
| DFS(0) | visit 0 → first unvisited neighbour 1 | 0 |
| DFS(1) | visit 1 → 0 seen, go to 2 | 0 1 |
| DFS(2) | visit 2 → 0, 1 seen, go to 4 | 0 1 2 |
| DFS(4) | visit 4 → 2 seen, go to 3 | 0 1 2 4 |
| DFS(3) | visit 3 → 1, 4 seen → backtrack | 0 1 2 4 3 |
Now watch it run
Every frame comes from really running the algorithm on your input — change it and break it! Tap ▶ Play, or step one frame at a time with ◀ ▶. Keys: Space play/pause, ← → step.
Also try: DFS
Algorithms
Both are ways to visit every vertex reachable from a start vertex exactly once. Breadth First Search (BFS) visits the start vertex, then all its neighbours, then their neighbours — level by level, using a queue. Depth First Search (DFS) goes as deep as possible along one path before backtracking, using recursion or an explicit stack.
Algorithm BFS(G, s)
1. for each vertex v: visited[v] ← false
2. visited[s] ← true; enqueue(s)
3. while queue not empty do
4. u ← dequeue(); print u
5. for each neighbour w of u in ascending order do
6. if not visited[w] then visited[w] ← true; enqueue(w)
Algorithm DFS(G, u) // call DFS(G, s) with all visited = false
1. visited[u] ← true; print u
2. for each neighbour w of u in ascending order do
3. if not visited[w] then DFS(G, w)In BFS mark a vertex visited when you put it in the queue, not when you take it out — otherwise the same vertex can enter the queue twice.
C implementation
graph_traversal.ctested ✓ 250/250 cases/* BFS and DFS on an adjacency matrix — KTU PCCST303, Module 3 (KTU Nov 2025 Q14a, May 2026 Q14a)
* Neighbours are taken in increasing vertex order, which makes the visit order unique —
* the convention KTU answer keys follow.
* Input : n m directed(0|1) then m edges "u v" (0..n-1) then the start vertex.
* Output: "BFS: ..." and "DFS: ..." (only vertices reachable from the start). */
#include <stdio.h>
#include <string.h>
#define MAXV 20
int adj[MAXV][MAXV], n, visited[MAXV];
void bfs(int s) {
int queue[MAXV], front = 0, rear = 0, u, v;
memset(visited, 0, sizeof visited);
visited[s] = 1;
queue[rear++] = s; /* mark when ENQUEUED, not when dequeued */
printf("BFS:");
while (front < rear) {
u = queue[front++];
printf(" %d", u);
for (v = 0; v < n; v++)
if (adj[u][v] && !visited[v]) { visited[v] = 1; queue[rear++] = v; }
}
printf("\n");
}
void dfs(int u) {
int v;
visited[u] = 1;
printf(" %d", u);
for (v = 0; v < n; v++)
if (adj[u][v] && !visited[v]) dfs(v); /* go deeper before trying the next neighbour */
}
int main(void) {
int m, directed, u, v, s, i;
if (scanf("%d %d %d", &n, &m, &directed) != 3 || n < 1 || n > MAXV) { printf("BAD INPUT\n"); return 1; }
for (i = 0; i < m; i++) {
if (scanf("%d %d", &u, &v) != 2 || u < 0 || v < 0 || u >= n || v >= n) { printf("BAD INPUT\n"); return 1; }
adj[u][v] = 1;
if (!directed) adj[v][u] = 1;
}
if (scanf("%d", &s) != 1 || s < 0 || s >= n) { printf("BAD INPUT\n"); return 1; }
bfs(s);
memset(visited, 0, sizeof visited);
printf("DFS:"); dfs(s); printf("\n");
return 0;
}
Sample run · lesson graph, start 0 · real output from gcc
Input (stdin)
5 6 0 0 1 0 2 1 2 1 3 2 4 3 4 0
Output (stdout)
BFS: 0 1 2 3 4 DFS: 0 1 2 4 3
Complexity
| Representation | BFS / DFS time |
|---|---|
| Adjacency list | O(n + e) |
| Adjacency matrix | O(n²) |
Asked in KTU exams (3)
- November 2025 · Q14a6 marksWrite algorithm for graph traversal using BFS. Perform BFS on the given graph from source vertex 0. If multiple choices may be available for the next node choose in ascending order.
- May 2026 · Q14a6 marksWrite algorithm for graph traversal using DFS. Perform DFS on the given graph from source vertex E.
- — 2024 · Q13a4 marksThe Breadth-First Search algorithm has been implemented with the help of a queue. What is a possible order of visiting the nodes of the following graph is
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- BFS: queue, level by level; mark on enqueue.
- DFS: recursion/stack, go deep, backtrack.
- Ties: smallest vertex first (as the question says).
- O(n + e) with lists, O(n²) with a matrix.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — §6.2 (Elementary graph operations)
- Cormen, Leiserson, Rivest & Stein, Introduction to Algorithms, 3/e — §22.2–22.3
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)