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

> What is DFS and BFS? A visual beginner's guide to graphs, stacks and queues, with DFS and BFS traced step by step on one graph and simple C++ code.

- Canonical URL: https://shafinchowdhury.dev/posts/what-is-dfs-and-bfs/
- Author: Shafin Chowdhury (https://shafinchowdhury.dev/about/)
- Published: 2026-12-04T03:30:00.000Z
- Updated: 2026-12-04T03:30:00.000Z
- Reading Time: 13 min read
- Tags: cpp, data-structures, graphs, algorithms, beginners

---

import Diagram from "@/components/Diagram.astro";
import TraversalPlayer from "@/components/TraversalPlayer.astro";

**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)$ 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](/posts/tree-binary-tree-traversals/), you have already seen DFS (preorder) and BFS (level order) on trees. Next: [DFS vs BFS: Complete Comparison](/posts/dfs-vs-bfs/).

---

## 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 thing | Nodes | Edges |
| --- | --- | --- |
| Facebook | People | Friendships |
| Google Maps | Intersections | Roads |
| The web | Pages | Links |
| A course plan | Courses | "must take before" |
| A maze | Junctions | Corridors |

<Diagram
  src="what-is-dfs-and-bfs/graph-basics"
  alt="An undirected graph with 7 nodes numbered 0 to 6 and 8 edges: 0–1, 0–2, 1–3, 1–4, 2–4, 2–5, 4–6 and 5–6. Node 4 is highlighted with its neighbours 1, 2 and 6."
/>

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 $V$ for the number of nodes (7).
- **Edge:** a connection between two nodes, such as 0–1. We write $E$ 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.

```text
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)$.

## The Two Helpers: Stack and Queue

<Diagram
  src="what-is-dfs-and-bfs/stack-and-queue"
  alt="Left: a stack holding A, B and C from bottom to top; you push and pop at the top, so popping gives C, the last item pushed. Right: a queue holding A, B and C from front to back; you enqueue at the back and dequeue at the front, so dequeuing gives A, the first item added."
/>

- A **[stack](/posts/understanding-stack-in-cpp/)** 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](/posts/understanding-queue-in-cpp/)** 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**.

## What Is DFS (Depth-First Search)?

**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.

| Step | What happens | Call stack | Visited so far |
| --- | --- | --- | --- |
| 1 | Visit **0**. First neighbour: 1 | 0 | 0 |
| 2 | Visit **1**. Neighbours 0 (visited), 3 → go to 3 | 0, 1 | 0 1 |
| 3 | Visit **3**. Only neighbour 1 is visited: dead end | 0, 1, 3 | 0 1 3 |
| 4 | Backtrack to 1. Next neighbour: 4 | 0, 1 | 0 1 3 |
| 5 | Visit **4**. Neighbours 1 (visited), 2 → go to 2 | 0, 1, 4 | 0 1 3 4 |
| 6 | Visit **2**. Neighbours 0, 4 visited; 5 → go to 5 | 0, 1, 4, 2 | 0 1 3 4 2 |
| 7 | Visit **5**. Neighbours 2 visited; 6 → go to 6 | 0, 1, 4, 2, 5 | 0 1 3 4 2 5 |
| 8 | Visit **6**. Neighbours 4, 5 visited: dead end | 0, 1, 4, 2, 5, 6 | 0 1 3 4 2 5 6 |
| 9 | Backtrack 6 → 5 → 2 → 4 → 1 → 0: nothing left anywhere | (empty) | done |

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

<Diagram
  src="what-is-dfs-and-bfs/dfs-step-by-step"
  alt="Seven small frames of the graph. Each frame highlights the node being visited in solid green, with previously visited nodes in light green: visit 0, then 1, 3, 4, 2, 5 and finally 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.

## What Is BFS (Breadth-First Search)?

**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.

| Step | Dequeue (visit) | Unvisited neighbours added | Queue after (front → back) |
| --- | --- | --- | --- |
| start | | 0 | 0 |
| 1 | **0** | 1, 2 | 1, 2 |
| 2 | **1** | 3, 4 | 2, 3, 4 |
| 3 | **2** | 5 (4 is already marked) | 3, 4, 5 |
| 4 | **3** | none | 4, 5 |
| 5 | **4** | 6 | 5, 6 |
| 6 | **5** | none (6 already marked) | 6 |
| 7 | **6** | none | (empty) |

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

<Diagram
  src="what-is-dfs-and-bfs/bfs-step-by-step"
  alt="Seven small frames of the graph for BFS. Each frame highlights the dequeued node in solid green, visited nodes in light green, and nodes waiting in the queue with a dashed outline: visit 0, then 1, 2, 3, 4, 5 and 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.

<TraversalPlayer
  graph
  orders={["dfs", "bfs"]}
  caption="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

```cpp
#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:**

```text
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**:

| | DFS | BFS |
| --- | --- | --- |
| Time | $O(V + E)$ | $O(V + E)$ |
| Extra space | $O(V)$: `visited` + call stack (up to $V$ deep) | $O(V)$: `visited` + queue (up to $V$ nodes) |

Why $O(V + E)$? Every node is visited once ($V$), 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)$ in total.

With an **adjacency matrix** (a $V \times V$ table of 0s and 1s), finding a node's neighbours means scanning a whole row, so both traversals take $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](/posts/dfs-vs-bfs/) 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)$ 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](/posts/dfs-vs-bfs/): explicit-stack DFS, shortest paths, cycle detection, connected components and interview questions.
2. Revisit trees with fresh eyes in [Trees, Binary Trees & Traversals](/posts/tree-binary-tree-traversals/): preorder is DFS, level order is BFS.
3. Brush up on the containers: [Stack in C++](/posts/understanding-stack-in-cpp/) and [Queue in C++](/posts/understanding-queue-in-cpp/).
