Skip to content
Azhimathi Mayam logoDSA Study HubPCCST303 · KTU · S3
Module 3 · syllabusAsked 3× in KTU papersLesson live

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
ormakkurippu ✎
Never-forget card

BFS = Queue = ripples spreading in a pond (level by level). DFS = Stack = exploring a cave: go deep, BACKTRACK when stuck.

Picture it

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.

Write this in the exam

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.

01342
Start vertex 0 highlighted.
BFS order: 0 1 2 3 4.
DequeueEnqueue (new)Queue afterVisited order
01, 21 20
13 (0, 2 already seen)2 30 1
243 40 1 2
3—40 1 2 3
4—empty0 1 2 3 4
DFS order: 0 1 2 4 3.
CallActionStack (recursion)
DFS(0)visit 0 → first unvisited neighbour 10
DFS(1)visit 1 → 0 seen, go to 20 1
DFS(2)visit 2 → 0, 1 seen, go to 40 1 2
DFS(4)visit 4 → 2 seen, go to 30 1 2 4
DFS(3)visit 3 → 1, 4 seen → backtrack0 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 ◀ ▶.

Loading visualizer…

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
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)
Watch outMark when you ENQUEUE

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
C
/* 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

Open in the Code Lab →

Complexity

Each vertex is visited once and each adjacency entry is examined once.
RepresentationBFS / DFS time
Adjacency listO(n + e)
Adjacency matrixO(n²)

Asked in KTU exams (3)

Quick check — can you get them all?

Question 1

Q1.Graph: 0–1, 0–2, 1–2, 1–3, 2–4, 3–4. BFS from 0 (ascending order)?

Question 2

Q2.Same graph. DFS from 0 (ascending order)?

Question 3

Q3.BFS uses a…

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)