Skip to content
Shafin Chowdhury
Go back

DFS vs BFS: Complete Comparison With C++ Code, Examples & Use Cases

Software Developer & Computer Science Student

Published:
15 min read
Edit page
Table of Contents8 topics

DFS vs BFS in short: DFS (depth-first search) explores a graph by going as deep as possible along one path before backtracking; it uses a stack (usually the recursion call stack). BFS (breadth-first search) explores level by level, visiting all nodes at distance 1, then distance 2, and so on; it uses a queue. Both take O(V+E)O(V + E) time with an adjacency list. The practical difference: BFS finds shortest paths in unweighted graphs; DFS is the natural fit for backtracking, cycle detection, topological sort and anything that needs to “finish” a branch.

This article compares the two algorithms side by side on the same graph: how they explore, their traversal orders, complexity and memory, and C++ implementations of the classic applications (shortest path, cycle detection, connected components), followed by the interview questions built on them.

Tree & Graph series, step 8 of 8. New to graphs? Start with What Are DFS and BFS?, which introduces graphs, stacks and queues from scratch.


Quick Comparison Table

FeatureDFSBFS
Data structureStack / recursionQueue
ExplorationDeep first, then backtrackLevel by level
Shortest pathNot generally guaranteedGuaranteed for unweighted graphs
Time (adjacency list)O(V+E)O(V + E)O(V+E)O(V + E)
Time (adjacency matrix)O(V2)O(V^2)O(V2)O(V^2)
Extra memoryProportional to the depth of the search, up to O(V)O(V)Proportional to the widest frontier, up to O(V)O(V); can be large for wide graphs
Typical codeRecursive (short)Iterative loop
Order on a treePreorder / inorder / postorderLevel order
ApplicationsBacktracking, cycle detection, topological sort, components, maze solvingShortest paths, levels/layers, nearest target, multi-source spread

What Is DFS?

Depth-first search starts at a source node and repeatedly moves to an unvisited neighbour of the most recently visited node. When the current node has no unvisited neighbours, DFS backtracks to the previous node on the path and continues from there.

What Is BFS?

Breadth-first search starts at a source node and visits all its neighbours before any of their neighbours. It keeps discovered-but-unprocessed nodes in a FIFO queue, so nodes are processed in non-decreasing distance from the source.

The Main Conceptual Difference

Both algorithms keep a frontier: nodes that have been discovered but whose neighbours have not been explored yet. They differ only in which frontier node they expand next:

  • DFS expands the newest frontier node (LIFO → stack).
  • BFS expands the oldest frontier node (FIFO → queue).

Replace the queue in BFS with a stack and you get (a form of) DFS. Everything else, the visited array and the neighbour loop, stays the same.

How They Explore the Same Graph

We use one undirected graph with 7 nodes and 8 edges: 0–1, 0–2, 1–3, 1–4, 2–4, 2–5, 4–6, 5–6, neighbours in increasing order, starting at 0.

Order from 0Edges used to reach new nodes
DFS0 1 3 4 2 5 60–1, 1–3, 1–4, 4–2, 2–5, 5–6
BFS0 1 2 3 4 5 60–1, 0–2, 1–3, 1–4, 2–5, 4–6

The highlighted edges form a spanning tree in each case: the DFS tree and the BFS tree. Look at node 2: BFS reaches it directly from 0 (distance 1), while DFS reaches it through 0 → 1 → 4 → 2 (depth 3). The DFS tree does not record shortest distances; the BFS tree does. That is the shortest-path property in one picture.

Step-by-step traversal example

Step through both on the same graph and compare the frontier (call stack, explicit stack, or queue):

0 1 2 3 4 5 6

Output
DFS (recursive), DFS with an explicit stack, and BFS from node 0 on the same graph.

Notice the explicit-stack DFS contains duplicates such as [2, 6, 6]: a node can be pushed by several neighbours before it is visited. It is marked when popped, and stale copies are skipped. This is what makes its order identical to the recursive version, at the cost of a stack that can hold up to O(E)O(E) entries. BFS marks nodes when enqueued, so each node enters the queue at most once.

How They Explore a Tree (vs a General Graph)

A rooted tree is a graph with no cycles where every node is reachable from the root by exactly one path. That changes three things:

Tree (from the root)General graph
Visited array needed?No: you only move from parent to child, so you can never revisit a nodeYes: cycles would cause infinite loops
DFS ordersPreorder, inorder, postorder (when you print relative to the recursive calls)Usually just “discovery order” (preorder) and “finish order” (postorder)
BFSLevel-order traversalVisits nodes by distance from the source
Reach everything from one start?Yes, from the rootOnly if the graph is connected

If a tree is given as an undirected edge list (common in competitive programming), you either keep a visited array or pass the parent and skip it, otherwise you walk straight back up the edge you came from. See the tree traversals guide for the tree-specific versions.

Complete C++ Implementation

The program below implements recursive DFS, DFS with an explicit stack, BFS, BFS shortest paths, connected components, and cycle detection for undirected and directed graphs. Each piece is explained in the sections that follow.

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

using Graph = vector<vector<int>>;

Graph undirected(int n, const vector<pair<int, int>>& edges) {
    Graph adj(n);
    for (auto [u, v] : edges) {
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    for (auto& list : adj) {
        sort(list.begin(), list.end()); // visit smaller neighbours first
    }
    return adj;
}

Graph directed(int n, const vector<pair<int, int>>& edges) {
    Graph adj(n);
    for (auto [u, v] : edges) {
        adj[u].push_back(v);
    }
    return adj;
}

// ---------- DFS using recursion ----------
void dfsRecursive(int u, const Graph& adj, vector<bool>& visited, vector<int>& order) {
    visited[u] = true;
    order.push_back(u);
    for (int v : adj[u]) {
        if (!visited[v]) {
            dfsRecursive(v, adj, visited, order);
        }
    }
}

// ---------- DFS using an explicit stack ----------
vector<int> dfsIterative(int start, const Graph& adj) {
    vector<bool> visited(adj.size(), false);
    vector<int> order;
    stack<int> st;
    st.push(start);
    while (!st.empty()) {
        int u = st.top();
        st.pop();
        if (visited[u]) {
            continue;            // stale duplicate entry
        }
        visited[u] = true;                   // mark when popped
        order.push_back(u);
        for (auto it = adj[u].rbegin(); it != adj[u].rend(); ++it) {
            if (!visited[*it]) {
                st.push(*it); // reverse, so the smallest is popped first
            }
        }
    }
    return order;
}

// ---------- BFS using a queue ----------
vector<int> bfs(int start, const Graph& adj) {
    vector<bool> visited(adj.size(), false);
    vector<int> order;
    queue<int> q;
    visited[start] = true;                   // mark when enqueued
    q.push(start);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        order.push_back(u);
        for (int v : adj[u]) {
            if (!visited[v]) {
                visited[v] = true;
                q.push(v);
            }
        }
    }
    return order;
}

// ---------- BFS shortest path (unweighted) ----------
// Fills dist (in edges, -1 = unreachable) and returns one shortest path source -> target.
vector<int> shortestPath(int source, int target, const Graph& adj, vector<int>& dist) {
    int n = adj.size();
    dist.assign(n, -1);
    vector<int> parent(n, -1);
    queue<int> q;
    dist[source] = 0;
    q.push(source);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : adj[u]) {
            if (dist[v] == -1) {             // first time seen = shortest distance
                dist[v] = dist[u] + 1;
                parent[v] = u;
                q.push(v);
            }
        }
    }
    vector<int> path;
    if (dist[target] == -1) {
        return path;     // unreachable
    }
    for (int v = target; v != -1; v = parent[v]) {
        path.push_back(v);
    }
    reverse(path.begin(), path.end());
    return path;
}

// ---------- Connected components (undirected) ----------
int countComponents(const Graph& adj) {
    vector<bool> visited(adj.size(), false);
    vector<int> ignored;
    int components = 0;
    for (int u = 0; u < (int)adj.size(); ++u) {
        if (!visited[u]) {                   // a new, untouched component
            ++components;
            dfsRecursive(u, adj, visited, ignored);
        }
    }
    return components;
}

// ---------- Cycle detection: undirected graph ----------
bool cycleFrom(int u, int parent, const Graph& adj, vector<bool>& visited) {
    visited[u] = true;
    for (int v : adj[u]) {
        if (!visited[v]) {
            if (cycleFrom(v, u, adj, visited)) {
                return true;
            }
        } else if (v != parent) {
            return true;                     // visited neighbour that isn't the edge we came from
        }
    }
    return false;
}
bool hasCycleUndirected(const Graph& adj) {
    vector<bool> visited(adj.size(), false);
    for (int u = 0; u < (int)adj.size(); ++u) {
        if (!visited[u] && cycleFrom(u, -1, adj, visited)) {
            return true;
        }
    }
    return false;
}

// ---------- Cycle detection: directed graph (white/gray/black) ----------
bool directedCycleFrom(int u, const Graph& adj, vector<int>& color) {
    color[u] = 1;                            // gray: on the current DFS path
    for (int v : adj[u]) {
        if (color[v] == 1) {
            return true;      // back edge to the current path
        }
        if (color[v] == 0 && directedCycleFrom(v, adj, color)) {
            return true;
        }
    }
    color[u] = 2;                            // black: fully explored
    return false;
}
bool hasCycleDirected(const Graph& adj) {
    vector<int> color(adj.size(), 0);        // white: unvisited
    for (int u = 0; u < (int)adj.size(); ++u) {
        if (color[u] == 0 && directedCycleFrom(u, adj, color)) {
            return true;
        }
    }
    return false;
}

void print(const char* label, const vector<int>& values) {
    cout << label;
    for (int x : values) {
        cout << x << ' ';
    }
    cout << '\n';
}

int main() {
    Graph g = undirected(7, {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 4}, {2, 5}, {4, 6}, {5, 6}});

    vector<bool> visited(7, false);
    vector<int> order;
    dfsRecursive(0, g, visited, order);
    print("DFS (recursive): ", order);
    print("DFS (stack):     ", dfsIterative(0, g));
    print("BFS (queue):     ", bfs(0, g));

    vector<int> dist;
    vector<int> path = shortestPath(0, 6, g, dist);
    print("Distances from 0: ", dist);
    print("Shortest path 0 -> 6: ", path);

    Graph forest = undirected(8, {{0, 1}, {1, 2}, {3, 4}, {5, 6}, {6, 7}});
    cout << "Connected components (8 nodes, 5 edges): " << countComponents(forest) << '\n';

    Graph tree = undirected(7, {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}, {4, 6}});
    cout << "Example graph has a cycle: " << (hasCycleUndirected(g) ? "yes" : "no") << '\n';
    cout << "Tree version has a cycle: " << (hasCycleUndirected(tree) ? "yes" : "no") << '\n';

    Graph loop = directed(3, {{0, 1}, {1, 2}, {2, 0}});
    Graph dag = directed(3, {{0, 1}, {0, 2}, {1, 2}});
    cout << "Directed 0->1->2->0 has a cycle: " << (hasCycleDirected(loop) ? "yes" : "no") << '\n';
    cout << "Directed 0->1, 0->2, 1->2 has a cycle: " << (hasCycleDirected(dag) ? "yes" : "no") << '\n';
}

Output:

DFS (recursive): 0 1 3 4 2 5 6
DFS (stack):     0 1 3 4 2 5 6
BFS (queue):     0 1 2 3 4 5 6
Distances from 0: 0 1 1 2 2 2 3
Shortest path 0 -> 6: 0 1 4 6
Connected components (8 nodes, 5 edges): 3
Example graph has a cycle: yes
Tree version has a cycle: no
Directed 0->1->2->0 has a cycle: yes
Directed 0->1, 0->2, 1->2 has a cycle: no

DFS using recursion

void dfsRecursive(int u, const Graph& adj, vector<bool>& visited, vector<int>& order) {
    visited[u] = true;
    order.push_back(u);
    for (int v : adj[u]) {
        if (!visited[v]) {
            dfsRecursive(v, adj, visited, order);
        }
    }
}

The call stack is the DFS stack: each active call is a node on the current path. When the loop finishes, the function returns, which is the backtrack. Short and clear, but the recursion depth can reach VV; on a path-shaped graph with 10510^5–10610^6 nodes this can overflow the default stack (often 1–8 MB). Use the iterative version for very deep graphs.

DFS using an explicit stack

Two details matter:

  1. Mark on pop, skip if already visited. Marking on push looks tempting but changes the order: it is no longer a true depth-first order, because a node pushed early by one neighbour can’t be “re-pushed” later by a deeper node.
  2. Push neighbours in reverse so the smallest neighbour is on top and gets explored first, matching the recursive order.

BFS using a queue

Mark on enqueue, not on dequeue. Marking on dequeue lets the same node enter the queue several times (in our graph, 4 would be enqueued by both 1 and 2), wasting time and memory.

Traversal Order Comparison

StartDFS orderBFS order
00 1 3 4 2 5 60 1 2 3 4 5 6
66 4 1 0 2 5 36 4 5 1 2 0 3
33 1 0 2 4 6 53 1 0 4 2 6 5

Both orders depend on the start node and the order of each neighbour list. Any order produced by the algorithm is a valid DFS/BFS order, so there is rarely a single “correct” answer unless the problem fixes the neighbour order (exams usually say “visit neighbours in increasing/alphabetical order”).

Time Complexity

Both are O(V+E)O(V + E) with an adjacency list:

  • Each vertex is marked and processed once: O(V)O(V).
  • Each vertex’s neighbour list is scanned once, when that vertex is processed. The lists together hold EE entries for a directed graph and 2E2E for an undirected one: O(E)O(E).

With an adjacency matrix, scanning a vertex’s neighbours means reading a whole row of VV entries, so both become O(V2)O(V^2). For sparse graphs (E≪V2E \ll V^2), which is most real graphs, adjacency lists are much faster.

Space Complexity

Both need O(V)O(V) for the visited array. The frontier is where they differ:

Graph shapeDFS frontierBFS frontier
Long path / chain of VV nodesO(V)O(V) deep (risk of stack overflow when recursive)O(1)O(1)
Star: one centre, V−1V - 1 leavesO(1)O(1) deepO(V)O(V): all leaves enqueued at once
Complete binary tree with VV nodesO(log⁡V)O(\log V)O(V)O(V) (the last level holds about V/2V/2 nodes)
Grid n×nn \times nup to O(n2)O(n^2)O(n)O(n) (one diagonal “wave”)

Rule of thumb: DFS memory grows with depth, BFS memory grows with width. For wide, shallow graphs (social networks, game trees with large branching factors), BFS can need far more memory. Iterative deepening DFS combines DFS’s small memory with BFS’s shortest-depth guarantee by running depth-limited DFS with limits 0, 1, 2, …

Advantages and Disadvantages

DFSBFS
AdvantagesVery short recursive code; low memory on wide graphs; natural for backtracking; gives discovery/finish times (topological sort, bridges, SCCs)Shortest path in unweighted graphs; finds the nearest target first; no recursion depth limit; naturally processes in levels
DisadvantagesNo shortest-path guarantee; recursion can overflow on deep graphs; can wander deep into a huge branch far from the targetMemory-hungry on wide graphs; slightly more code; not suited to backtracking

Real-World Applications

DFS:

  • Backtracking search: Sudoku and N-Queens solvers, generating permutations and subsets.
  • Cycle detection: deadlock detection, circular imports, spreadsheet formula loops.
  • Topological sort: build systems and package managers ordering dependencies (reverse postorder of DFS).
  • Connectivity: connected components, articulation points and bridges (critical routers and links), strongly connected components (Tarjan, Kosaraju).
  • Maze generation and solving, flood fill in paint programs.

BFS:

  • Shortest paths in unweighted graphs: fewest hops in a network, fewest moves in a puzzle, word ladder.
  • Social networks: “people you may know” (friends of friends), degrees of separation.
  • Web crawling near a seed page; broadcasting in networks.
  • Multi-source BFS: distance to the nearest hospital or exit for every cell, fire or infection spread (rotting oranges).
  • GPS on uniform grids, robot navigation when all moves cost the same.
  • Bipartite checking (two-colouring level by level).

When Should You Use DFS?

  • You need to explore all possibilities or backtrack (puzzles, permutations, paths).
  • You need cycle detection, topological order, or strongly connected components.
  • You only need to know whether something is reachable, not how far it is; DFS is shortest to write.
  • The graph is wide and memory matters.
  • You need postorder information: a node’s answer depends on its children’s answers (subtree sizes, tree DP).

When Should You Use BFS?

  • You need the shortest path or minimum number of steps in an unweighted graph.
  • You need things by level: level-order traversal, nodes at distance kk, “minimum depth”.
  • The target is probably close to the start, and the graph is very deep or infinite; BFS will not get lost down one branch.
  • You have multiple sources spreading simultaneously.
  • The graph can be extremely deep and recursion would overflow.

Shortest Path in an Unweighted Graph

Why BFS works. BFS dequeues nodes in non-decreasing order of distance: all distance-dd nodes are processed before any distance-(d+1)(d+1) node. So the first time a node is discovered, it is discovered from a node at the smallest possible distance, and dist[v] = dist[u] + 1 is final. Storing parent[v] = u lets you walk back from the target to rebuild one shortest path (0 → 1 → 4 → 6 here).

Why DFS doesn’t. DFS discovers node 2 at depth 3 (through 0 → 1 → 4 → 2) even though 2 is adjacent to 0. DFS can find shortest paths only by exploring every path, which is exponential in general.

Important limits:

  • BFS gives shortest paths only when every edge has the same weight (or no weight).
  • Weighted graphs with non-negative weights need Dijkstra’s algorithm (a priority queue instead of a plain queue).
  • Weights of only 0 and 1: 0-1 BFS with a deque.
  • Negative weights: Bellman-Ford.

Cycle Detection

Undirected graphs. Run DFS and remember the parent. If you meet a visited neighbour that is not your parent, there is a cycle. (The parent is excluded because the edge you arrived on always leads back to a visited node.) In our graph DFS goes 0 → 1 → 3, backtracks, then 1 → 4 → 2, and at 2 finds neighbour 0: visited and not the parent (4), so it reports a cycle. BFS can detect undirected cycles the same way.

Directed graphs. “Visited” is not enough, because in 0→1, 0→2, 1→2 node 2 is reached twice without any cycle. Use three colours: white (unvisited), gray (on the current recursion path), black (finished). A cycle exists iff DFS finds an edge to a gray node (a back edge). For directed graphs, BFS-based Kahn’s algorithm is the alternative: if a topological sort cannot include every node, there is a cycle.

Connected Components

Loop over all vertices; whenever you find an unvisited one, it starts a new component, and one DFS (or BFS) from it marks the whole component. The number of times you start a traversal is the number of components. In the program, the graph with edges 0–1, 1–2, 3–4, 5–6, 6–7 has three components: {0, 1, 2}, {3, 4}, {5, 6, 7}. Total time is still O(V+E)O(V + E), because each vertex and edge is handled once across all the traversals. An alternative for dynamic connectivity is Union-Find (DSU).

Common Interview Questions

QuestionUseWhy
Number of Islands (LeetCode 200)DFS or BFSCount components on a grid
Flood Fill (LeetCode 733)DFSRecolour one component
Rotting Oranges (LeetCode 994)Multi-source BFSMinutes = BFS levels
Word Ladder (LeetCode 127)BFSFewest transformations = shortest path
Course Schedule (LeetCode 207)DFS colours or Kahn’s BFSCycle in a directed graph
Clone Graph (LeetCode 133)DFS or BFS + hash mapVisit every node once, map old to new
Is Graph Bipartite? (LeetCode 785)BFS or DFS colouringAdjacent nodes need different colours
Number of Provinces (LeetCode 547)DFSComponents from an adjacency matrix
Find if Path Exists in Graph (LeetCode 1971)DFS / BFSReachability
Binary Tree Level Order Traversal (LeetCode 102)BFSLevels

Conceptual questions interviewers ask:

  1. “Why mark visited when enqueuing in BFS?” To stop the same node from entering the queue several times; with marking on dequeue, the queue can grow to O(E)O(E) and nodes get processed repeatedly.
  2. “Can DFS find the shortest path?” Not in general. It finds a path. In a tree, the unique path is also the shortest, so DFS works there.
  3. “What if the graph doesn’t fit in memory or is infinite?” BFS (or iterative deepening) from the start, stopping at the target; DFS may never return from an infinite branch.
  4. “Recursive DFS crashed on a big input. Why?” Stack overflow from recursion depth O(V)O(V); switch to an explicit stack.
  5. “What’s the complexity of BFS on a grid?” O(R⋅C)O(R \cdot C): each cell is a vertex with at most 4 edges.
  6. “How do you print the levels separately in BFS?” Record q.size() at the start of each level and process exactly that many nodes (see tree interview question 20).

Frequently Asked Questions

Is DFS or BFS better?

Neither is better in general: both are O(V+E)O(V + E). Choose BFS when you need shortest paths or levels in an unweighted graph; choose DFS for backtracking, cycle detection, topological sort, or when the graph is wide and memory is tight.

Why is DFS implemented with recursion?

The recursion call stack naturally remembers the path to backtrack along, so the code is very short. The trade-off is the recursion depth limit on very deep graphs.

Does BFS work on weighted graphs?

It still visits every node, but it no longer gives shortest paths, because the fewest edges is not the smallest total weight. Use Dijkstra’s algorithm for non-negative weights.

Are DFS and BFS used on trees?

Yes. Preorder, inorder and postorder traversals are DFS; level-order traversal is BFS. Trees need no visited array because they have no cycles.

Next Steps

You have completed the series. To keep practising:

  1. Revisit the beginner’s guide to DFS and BFS and try its exercises from different start nodes.
  2. Apply BFS to trees in the tree interview questions (level order, minimum depth) and solve queue-based problems in Top 5 Queue Problems in C++.
  3. Review why DFS needs a stack and BFS a queue in Queue vs Stack in C++.

Edit page
Share this post:

Related Articles

Continue exploring related topics and foundational concepts.

9 min read

Queue vs Stack in C++: LIFO vs FIFO, STL & Practical Comparison

Understand the difference between Queue and Stack in C++. Compare FIFO vs LIFO ordering, insertion and deletion ends, accessible elements, std::queue vs std::stack in C++ STL, visual element traces, time complexity, and when to use each.

Read Article
13 min read

Top 5 Famous Queue Problems in Competitive Programming (With C++ Solutions)

Master the 5 most famous Queue and Deque problems in competitive programming and coding interviews: Implement Queue Using Stacks, Number of Recent Calls, Binary Tree Level Order Traversal, Rotten Oranges (BFS), and Sliding Window Maximum (Monotonic Deque)—complete with C++ code and dry runs.

Read Article

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