Skip to content
Shafin Chowdhury
Go back

What Are DFS and BFS? A Visual Beginner's Guide to Graph Traversal (C++)

Software Developer & Computer Science Student

Published:
13 min read
Edit page
Table of Contents9 topics

DFS (Depth-First Search) and BFS (Breadth-First Search) are the two basic ways to visit every node of a graph. DFS follows one path as deep as it can go, then backs up and tries the next path; it uses a stack (or recursion). BFS visits all nearby nodes first, then the nodes one step farther, and so on, level by level; it uses a queue. Both visit every reachable node once and run in O(V+E)O(V + E) time.

If you have never studied graph algorithms, this guide starts from zero: what a graph is, how a computer stores one, and then DFS and BFS traced step by step on the same small graph, with an interactive player and beginner-friendly C++.

Tree & Graph series, step 7 of 8. No tree knowledge is required, but if you have read Tree Traversals, you have already seen DFS (preorder) and BFS (level order) on trees. Next: DFS vs BFS: Complete Comparison.


Start With an Analogy

Imagine you are exploring a building full of rooms connected by corridors, looking for every room.

  • DFS is the maze explorer. You pick a corridor and keep walking, always taking the next unexplored corridor, until you hit a dead end. Then you walk back to the last junction that still has an unexplored corridor and continue from there. You go deep first.
  • BFS is the ripple in a pond. You first visit every room that is one corridor away from the entrance. Then every room two corridors away. Then three. You spread out in layers, like a ripple.

Both explorers eventually visit every room. They differ only in the order they visit them, and that order is what makes each one useful for different problems.

What Is a Graph?

A graph is a set of nodes (also called vertices) connected by edges. That’s all. It can model almost anything with connections:

Real thingNodesEdges
FacebookPeopleFriendships
Google MapsIntersectionsRoads
The webPagesLinks
A course planCourses”must take before”
A mazeJunctionsCorridors

This is the graph we will use for every example. It has 7 nodes (0 to 6) and 8 edges.

Nodes and edges: the words you need

  • Node / vertex: a point in the graph. Here: 0, 1, …, 6. We write VV for the number of nodes (7).
  • Edge: a connection between two nodes, such as 0–1. We write EE for the number of edges (8).
  • Neighbours (adjacent nodes): nodes joined by an edge. The neighbours of 4 are 1, 2 and 6.
  • Undirected vs directed: in an undirected graph, edges work both ways (friendships). In a directed graph, an edge goes one way (following someone on Instagram). Our example is undirected.
  • Path: a sequence of nodes joined by edges, like 0 → 1 → 4 → 6.
  • Cycle: a path that comes back to where it started, like 0 → 1 → 4 → 2 → 0. Cycles are why graph traversal needs extra care, as you will see in a moment.

A tree is just a special graph: connected, with no cycles.

How a computer stores a graph: the adjacency list

The most common way is an adjacency list: for each node, keep a list of its neighbours.

0: 1 2
1: 0 3 4
2: 0 4 5
3: 1
4: 1 2 6
5: 2 6
6: 4 5

In C++ this is a vector<vector<int>>: adj[4] is the list {1, 2, 6}. Because the graph is undirected, every edge appears twice (0–1 is in adj[0] and in adj[1]). We keep each list in increasing order, so “visit neighbours in order” always means smallest first.

What Is Graph Traversal?

Graph traversal means visiting every node you can reach from a starting node, exactly once. It is the foundation of almost every graph algorithm: finding a route, checking whether a network is connected, detecting loops, solving mazes.

Why do we need a “visited” array?

Look at the cycle 0 → 1 → 4 → 2 → 0. If you simply “go to every neighbour”, you would walk 0 → 1 → 4 → 2 → 0 → 1 → … forever. Trees never have this problem (no cycles), but graphs do.

The fix is a visited array of booleans: mark a node as visited the first time you reach it, and never process a visited node again. That single rule guarantees each node is handled once, which is also why the running time is O(V+E)O(V + E).

The Two Helpers: Stack and Queue

  • A stack is Last In, First Out (LIFO), like a pile of plates: you always take the one you put down most recently. DFS uses a stack because it always continues from the newest place it found.
  • Recursion uses a stack too: the computer’s call stack. When a function calls itself, the current call waits on the stack until the inner call returns. That is why DFS is usually written recursively; the call stack does the remembering.
  • A queue is First In, First Out (FIFO), like a line at a bank: whoever arrived first is served first. BFS uses a queue because it serves nodes in the order they were discovered, which is nearest first.

That is the entire difference between DFS and BFS: stack vs queue.

DFS starts at a node, marks it visited, then immediately moves to its first unvisited neighbour, and from there to that node’s first unvisited neighbour, and so on. When it reaches a node with no unvisited neighbours, it backtracks to the previous node and tries its next neighbour.

How DFS works, step by step

Start at node 0. Neighbours are always tried in increasing order. The call stack column shows the path DFS is currently on.

StepWhat happensCall stackVisited so far
1Visit 0. First neighbour: 100
2Visit 1. Neighbours 0 (visited), 3 → go to 30, 10 1
3Visit 3. Only neighbour 1 is visited: dead end0, 1, 30 1 3
4Backtrack to 1. Next neighbour: 40, 10 1 3
5Visit 4. Neighbours 1 (visited), 2 → go to 20, 1, 40 1 3 4
6Visit 2. Neighbours 0, 4 visited; 5 → go to 50, 1, 4, 20 1 3 4 2
7Visit 5. Neighbours 2 visited; 6 → go to 60, 1, 4, 2, 50 1 3 4 2 5
8Visit 6. Neighbours 4, 5 visited: dead end0, 1, 4, 2, 5, 60 1 3 4 2 5 6
9Backtrack 6 → 5 → 2 → 4 → 1 → 0: nothing left anywhere(empty)done

DFS order from 0: 0 1 3 4 2 5 6

Notice how DFS dives from 4 to 2 instead of returning to 0 to try 2 from there: it always continues from the most recent node.

BFS starts at a node, then visits all of its neighbours, then all of their unvisited neighbours, and so on. It explores the graph in levels: level 0 is the start, level 1 is everything one edge away, level 2 is everything two edges away.

How BFS works, step by step

Rule: mark a node visited when you put it into the queue, so it can never be added twice.

StepDequeue (visit)Unvisited neighbours addedQueue after (front → back)
start00
101, 21, 2
213, 42, 3, 4
325 (4 is already marked)3, 4, 5
43none4, 5
5465, 6
65none (6 already marked)6
76none(empty)

BFS order from 0: 0 1 2 3 4 5 6, by levels: 0 | 1 2 | 3 4 5 | 6.

The dashed nodes in each frame are in the queue: discovered but not yet visited. Notice that 3, 4 and 5, all two edges from 0, are visited before 6, which is three edges away. BFS always finishes a level before starting the next one.

Try It Yourself: Interactive DFS and BFS

Switch between DFS and BFS on the same graph and step through each move. Watch the call stack grow and shrink during DFS, and the queue fill from the back and empty from the front during BFS. Thick green edges are the ones the traversal used to reach a new node.

0 1 2 3 4 5 6

Output
DFS and BFS from node 0 on the 7-node example graph. Step through or press Play to compare the order in which nodes are visited.

Beginner-Friendly C++ Implementation

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

// DFS: visit a node, then go deep into each unvisited neighbour.
void dfs(int node, const vector<vector<int>>& adj, vector<bool>& visited) {
    visited[node] = true;                 // mark first, so we never come back
    cout << node << ' ';
    for (int next : adj[node]) {
        if (!visited[next]) {
            dfs(next, adj, visited);      // go deeper; returns when that branch is done
        }
    }
}

// BFS: visit nodes level by level using a queue.
void bfs(int start, const vector<vector<int>>& adj) {
    vector<bool> visited(adj.size(), false);
    queue<int> q;
    visited[start] = true;                // mark when added to the queue
    q.push(start);

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        cout << node << ' ';
        for (int next : adj[node]) {
            if (!visited[next]) {
                visited[next] = true;
                q.push(next);
            }
        }
    }
}

int main() {
    int n = 7; // nodes 0..6
    vector<pair<int, int>> edges = {
        {0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 4}, {2, 5}, {4, 6}, {5, 6}
    };

    // Build the adjacency list. Undirected: add each edge in both directions.
    vector<vector<int>> adj(n);
    for (auto [u, v] : edges) {
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    vector<bool> visited(n, false);
    cout << "DFS from 0: ";
    dfs(0, adj, visited);
    cout << '\n';

    cout << "BFS from 0: ";
    bfs(0, adj);
    cout << '\n';
}

Output:

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

How the pieces connect:

  • adj is built so that adj[u] lists the neighbours of u. The edges were listed so that each list comes out in increasing order, matching the hand traces.
  • dfs is recursive. The base case is implicit: when every neighbour is already visited, the loop does nothing and the function returns, which is the “backtrack” step.
  • bfs is a loop with a queue. It stops when the queue is empty, meaning there is nothing left to discover.
  • Both use visited so each node is processed once, even though this graph has cycles.

If the neighbours were stored in a different order, both traversals would still be correct but would print different orders. DFS and BFS orders are not unique; they depend on the start node and the neighbour order.

Time and Space Complexity

With an adjacency list:

DFSBFS
TimeO(V+E)O(V + E)O(V+E)O(V + E)
Extra spaceO(V)O(V): visited + call stack (up to VV deep)O(V)O(V): visited + queue (up to VV nodes)

Why O(V+E)O(V + E)? Every node is visited once (VV), and when a node is visited we scan its neighbour list once. All the neighbour lists together contain each edge twice in an undirected graph, so the scanning costs O(E)O(E) in total.

With an adjacency matrix (a V×VV \times V table of 0s and 1s), finding a node’s neighbours means scanning a whole row, so both traversals take O(V2)O(V^2).

Applications

DFS is used for:

  • Solving mazes and puzzles (try a path, backtrack if stuck): the basis of backtracking (N-Queens, Sudoku solvers).
  • Detecting cycles (for example, deadlocks or circular dependencies).
  • Topological sorting: ordering tasks so that prerequisites come first.
  • Finding connected components and checking connectivity.
  • Tree traversals: preorder, inorder and postorder are all DFS.

BFS is used for:

  • Shortest path in an unweighted graph (fewest roads, fewest clicks, fewest moves).
  • “Degrees of separation” in social networks (friends of friends).
  • Web crawlers that explore pages near the start page first.
  • Level-order traversal of trees.
  • Spreading processes: rotting oranges, fire spread, multi-source flood fill.

The DFS vs BFS comparison goes deeper into when to choose which, with code for shortest paths, cycle detection and connected components.

Practice Exercises

Use the example graph and start from node 0 unless told otherwise. Answers are below.

  1. Write the DFS order starting from node 6.
  2. Write the BFS order starting from node 6.
  3. Remove the edge 2–4. What are the DFS and BFS orders from 0 now?
  4. In BFS from 0, how many edges is node 6 from node 0? Which path does BFS find?
  5. Add a new node 7 with no edges. What do DFS and BFS from 0 print? Why?
  6. True or false: DFS from 0 always visits node 3 before node 2.

Answers.

  1. DFS from 6: 6 → 4 → 1 → 0 → 2 → 5, then back up to 1 to visit 3. Order: 6 4 1 0 2 5 3.
  2. BFS from 6: level 0: 6; level 1: 4, 5; level 2: 1, 2; level 3: 0, 3. Order: 6 4 5 1 2 0 3.
  3. DFS: 0 1 3 4 6 5 2; BFS: 0 1 2 3 4 5 6 (the order is unchanged even though the edge is gone; check the levels).
  4. 3 edges, path 0 → 1 → 4 → 6.
  5. The same 7 nodes as before; node 7 is never printed because it is not reachable from 0. To visit every node of a disconnected graph, start a new traversal from each unvisited node; that is how connected components are counted.
  6. True for this graph with neighbours in increasing order, but not in general: it depends on neighbour order. If adj[0] were {2, 1}, DFS would reach 2 first.

Frequently Asked Questions

What is the main difference between DFS and BFS?

DFS goes as deep as possible along one path before backtracking and uses a stack or recursion. BFS visits nodes level by level and uses a queue.

Which is faster, DFS or BFS?

Neither: both take O(V+E)O(V + E) time. The choice depends on the problem, for example BFS for shortest paths in unweighted graphs, DFS for backtracking and cycle detection.

Why does DFS use a stack and BFS a queue?

DFS must return to the most recent junction when it gets stuck (last in, first out). BFS must process nodes in the order they were found, so nearer nodes come before farther ones (first in, first out).

Do I need a visited array for trees?

Not for a rooted tree traversed from parent to child, because there are no cycles. If you store a tree as an undirected graph, you need either a visited array or the parent node, to avoid walking back up the edge you came from.

Next Steps

  1. Next: DFS vs BFS: Complete Comparison: explicit-stack DFS, shortest paths, cycle detection, connected components and interview questions.
  2. Revisit trees with fresh eyes in Trees, Binary Trees & Traversals: preorder is DFS, level order is BFS.
  3. Brush up on the containers: Stack in C++ and Queue in C++.

Edit page
Share this post:

Related Articles

Continue exploring related topics and foundational concepts.

10 min read

Understanding Queue in C++: Complete Beginner's Guide

Learn the Queue data structure in C++ from scratch. Understand the FIFO (First-In, First-Out) principle, core Queue operations (enqueue, dequeue, front, rear, empty, size), std::queue in C++ STL, real-world examples, and time complexity.

Read Article
12 min read

Stack in C++: Complete Beginner's Guide

A stack in C++ stores elements in LIFO order, so push, pop and top all work on one end. Learn each operation and std::stack with a full example.

Read Article

Previous Post
DFS vs BFS: Complete Comparison With C++ Code, Examples & Use Cases
Next Post
Binary Search Tree (BST) Questions for University Exams in Bangladesh: Construction, Deletion & Viva (With Answers)