CrushThichThangBanThan's blog

By CrushThichThangBanThan, history, 4 days ago, In English

Understanding BFS and DFS: A Beginner's Guide to Graph Traversal

1. Introduction

Have you ever wondered how a computer explores a maze, finds a path between two cities, or visits every connected point in a network?

These problems often involve Graph Traversal.

Graph traversal is the process of visiting vertices (also called nodes) in a graph while following its edges. Two of the most important graph traversal algorithms are:

  • BFS (Breadth-First Search)
  • DFS (Depth-First Search)

Both algorithms help us explore graphs, but they work in different ways.

In this blog, we will learn how BFS and DFS work, how to implement them in C++, and when to use each algorithm.


2. What Is a Graph?

Before learning BFS and DFS, we need to understand what a graph is.

A graph is a data structure consisting of:

  • Vertices (Nodes): The objects or points in the graph.
  • Edges: The connections between vertices.

For example, consider this graph:

    1
   / \
  2   3
 /     \
4       5

We can represent it using an adjacency list:

1: 2, 3
2: 1, 4
3: 1, 5
4: 2
5: 3

An adjacency list stores the neighbors of each vertex. It is one of the most common ways to represent graphs in competitive programming.

C++ Implementation

#include <bits/stdc++.h>
using namespace std;

const int N = 100005;

vector<int> adj[N];

int main() {
    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
        int u, v;
        cin >> u >> v;

        adj[u].push_back(v);
        adj[v].push_back(u); // Undirected graph
    }

    return 0;
}

Here:

  • n is the number of vertices.
  • m is the number of edges.
  • adj[u] contains all neighbors of vertex u.

For a directed graph, we only need to add v to adj[u], without adding u to adj[v].


3. Breadth-First Search (BFS)

3.1. What Is BFS?

Breadth-First Search (BFS) is a graph traversal algorithm that explores vertices level by level.

Instead of going as deep as possible, BFS visits all nearby vertices before moving farther away.

BFS uses a data structure called a Queue.

A queue follows the FIFO principle:

First In, First Out.

The first element inserted into the queue will be the first element removed.

3.2. How Does BFS Work?

Let's use the following graph:

    1
   / \
  2   3
 / \   \
4   5   6

Suppose we start BFS from vertex 1.

The traversal process looks like this:

Step 1: Visit vertex 1 and add its neighbors to the queue.

Queue: [2, 3]
Visited: {1, 2, 3}

Step 2: Remove 2 from the queue and explore its neighbors.

Queue: [3, 4, 5]
Visited: {1, 2, 3, 4, 5}

Step 3: Remove 3 and explore its unvisited neighbors.

Queue: [4, 5, 6]
Visited: {1, 2, 3, 4, 5, 6}

Step 4: Continue until the queue becomes empty.

The BFS traversal order is:

1 -> 2 -> 3 -> 4 -> 5 -> 6

The exact order can change depending on the order in which neighbors are stored.

3.3. BFS Implementation in C++

#include <bits/stdc++.h>
using namespace std;

const int N = 100005;

vector<int> adj[N];
bool visited[N];

void BFS(int start) {
    queue<int> q;

    visited[start] = true;
    q.push(start);

    while (!q.empty()) {
        int u = q.front();
        q.pop();

        cout << u << " ";

        for (int v : adj[u]) {
            if (!visited[v]) {
                visited[v] = true;
                q.push(v);
            }
        }
    }
}

int main() {
    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
        int u, v;
        cin >> u >> v;

        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    BFS(1);

    return 0;
}

3.4. Important Things to Remember

There are three important steps in BFS:

  1. Create a queue.
  2. Mark a vertex as visited when you insert it into the queue.
  3. Continue exploring until the queue is empty.

Why do we mark a vertex as visited when pushing it into the queue?

Because this prevents the same vertex from being inserted multiple times by different neighbors.

3.5. Applications of BFS

BFS is especially useful for:

  • Finding the shortest path in an unweighted graph.
  • Finding the minimum number of moves in a game.
  • Finding the minimum distance from a starting vertex.
  • Exploring a grid or maze level by level.
  • Finding connected components.

For example, if every edge has the same cost, BFS can find the shortest path in terms of the number of edges.


4. Depth-First Search (DFS)

4.1. What Is DFS?

Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along one path before going back.

Unlike BFS, DFS does not explore the graph level by level.

DFS commonly uses:

  • Recursion, which relies on the function call stack.
  • An explicit stack, which we manage ourselves.

Think of DFS as exploring a maze: you choose a path, keep going until you cannot continue, and then return to an earlier point to try another path.

4.2. How Does DFS Work?

Consider the same graph:

    1
   / \
  2   3
 / \   \
4   5   6

Suppose we start DFS from vertex 1.

One possible traversal is:

1 -> 2 -> 4 -> 5 -> 3 -> 6

Here is how it works:

  1. Start at vertex 1.
  2. Move to vertex 2.
  3. Move deeper to vertex 4.
  4. Vertex 4 has no unvisited neighbors, so return to 2.
  5. Visit vertex 5.
  6. Return to 1.
  7. Visit vertex 3.
  8. Move to vertex 6.

The traversal order depends on the order of neighbors in the adjacency list.

4.3. Recursive DFS Implementation in C++

#include <bits/stdc++.h>
using namespace std;

const int N = 100005;

vector<int> adj[N];
bool visited[N];

void DFS(int u) {
    visited[u] = true;

    cout << u << " ";

    for (int v : adj[u]) {
        if (!visited[v]) {
            DFS(v);
        }
    }
}

int main() {
    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
        int u, v;
        cin >> u >> v;

        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    DFS(1);

    return 0;
}

4.4. Understanding Recursion in DFS

The most important part of DFS is:

for (int v : adj[u]) {
    if (!visited[v]) {
        DFS(v);
    }
}

What happens here?

  • Check every neighbor of the current vertex.
  • If a neighbor has not been visited, call DFS on it.
  • The current function pauses while the recursive call explores another part of the graph.
  • When the recursive call finishes, the previous function continues.

This is how DFS goes deeper and then backtracks.

4.5. Iterative DFS Using a Stack

DFS can also be implemented without recursion by using a stack.

void DFS_Iterative(int start) {
    stack<int> st;

    st.push(start);

    while (!st.empty()) {
        int u = st.top();
        st.pop();

        if (visited[u]) continue;

        visited[u] = true;
        cout << u << " ";

        for (int v : adj[u]) {
            if (!visited[v]) {
                st.push(v);
            }
        }
    }
}

An iterative implementation is useful when the graph is very deep and recursive DFS might cause a stack overflow.

Notice that this version marks vertices as visited when they are removed from the stack. A vertex may therefore be pushed more than once.

4.6. Applications of DFS

DFS is useful for:

  • Finding connected components.
  • Detecting cycles in graphs.
  • Topological sorting in directed acyclic graphs.
  • Finding paths between vertices.
  • Exploring all reachable vertices.
  • Solving maze and backtracking problems.

5. BFS vs DFS: What Is the Difference?

Both BFS and DFS can explore every reachable vertex, but their strategies are different.

Feature BFS DFS
Full name Breadth-First Search Depth-First Search
Main data structure Queue Stack / Recursion
Exploration strategy Level by level Go as deep as possible
Shortest path in an unweighted graph Yes Not guaranteed
Common applications Shortest paths, levels Cycle detection, backtracking
Time complexity O(V + E) O(V + E)

Where:

  • V is the number of vertices.
  • E is the number of edges.

With an adjacency list, both algorithms have a time complexity of O(V + E), because each vertex and edge is processed only a constant number of times.

Their auxiliary space complexity is also O(V) for the visited array and traversal data structure, excluding the graph representation.


6. A Complete Example

Let's practice with a simple problem.

Problem

You are given an undirected graph with n vertices and m edges.

Your task is to print the vertices reachable from vertex 1 using BFS and DFS.

Input

6 5
1 2
1 3
2 4
2 5
3 6

Graph

    1
   / \
  2   3
 / \   \
4   5   6

C++ Solution

#include <bits/stdc++.h>
using namespace std;

const int N = 100005;

int n, m;
vector<int> adj[N];
bool visited[N];

void BFS(int start) {
    queue<int> q;

    fill(visited, visited + n + 1, false);

    visited[start] = true;
    q.push(start);

    while (!q.empty()) {
        int u = q.front();
        q.pop();

        cout << u << " ";

        for (int v : adj[u]) {
            if (!visited[v]) {
                visited[v] = true;
                q.push(v);
            }
        }
    }

    cout << '\n';
}

void DFS(int u) {
    visited[u] = true;

    cout << u << " ";

    for (int v : adj[u]) {
        if (!visited[v]) {
            DFS(v);
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
        int u, v;
        cin >> u >> v;

        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    cout << "BFS: ";
    BFS(1);

    fill(visited, visited + n + 1, false);

    cout << "DFS: ";
    DFS(1);

    return 0;
}

Output

BFS: 1 2 3 4 5 6
DFS: 1 2 4 5 3 6

The output assumes neighbors are processed in the same order as they appear in the input.


7. Common Mistakes Beginners Should Avoid

When learning BFS and DFS, beginners often make the following mistakes:

1. Forgetting the visited array

Without visited, an undirected graph can cause infinite traversal between two connected vertices.

2. Marking vertices at the wrong time in BFS

Mark a vertex as visited when adding it to the queue to prevent duplicate insertions.

3. Forgetting disconnected components

Calling BFS(1) or DFS(1) only explores vertices reachable from vertex 1.

To traverse the entire graph, use:

for (int i = 1; i <= n; i++) {
    if (!visited[i]) {
        DFS(i);
    }
}

This also helps you count connected components.

4. Using recursive DFS on a very deep graph

For large graphs, recursion may exceed the call stack limit. Consider iterative DFS when necessary.

5. Assuming DFS always finds the shortest path

DFS explores one path deeply before exploring alternatives. It does not guarantee the shortest path in an unweighted graph. BFS is usually the right choice for that task.


8. Practice Problems

The best way to understand BFS and DFS is to solve problems.

Here are some beginner-friendly problems to practice:

  1. CSES – Counting Rooms — Practice DFS or BFS on a grid.
  2. CSES – Building Roads — Find connected components.
  3. CSES – Message Route — Use BFS to find a shortest path.
  4. Codeforces Problemset — Search for beginner-level graph traversal problems.

Try solving each problem using both BFS and DFS whenever possible.


9. Final Thoughts

BFS and DFS are two fundamental algorithms that every competitive programmer should understand.

Remember these simple ideas:

  • BFS = Queue = Explore level by level.
  • DFS = Stack or Recursion = Explore as deeply as possible.

Do not try to memorize the code without understanding how it works. Learn how vertices are visited, how the queue or stack changes, and why the visited array is necessary.

Once you understand these two algorithms, you will have a strong foundation for more advanced graph topics such as Dijkstra's Algorithm, Topological Sorting, Minimum Spanning Trees, and Strongly Connected Components.

Keep practicing, and good luck on your competitive programming journey!

  • Vote: I like it
  • -5
  • Vote: I do not like it