C++ · Module 18 · Lesson 51 min read

Graphs: BFS & DFS

Graph vocabulary

  • Vertices (nodes) and edges (connections)
  • Directed (one-way) vs undirected
  • Weighted (distance, cost) vs unweighted
  • Path, cycle, connected component, degree

Representations

Adjacency list ✅Adjacency matrix
Structurestd::vector<std::vector<int>> adj(n)std::vector<std::vector<bool>>(n, n)
MemoryO(V + E)O(V²)
Check edge u–vO(degree)O(1)
Best forsparse graphs (most real ones)dense graphs
With names instead of numbers: std::unordered_map<std::string, std::vector<std::string>>.

Breadth-First Search (BFS) — level by level

Uses a queue. Visits all neighbours at distance 1, then 2, …

  • Finds the shortest path (fewest edges) in an unweighted graph ✅
  • Track visited (or distance = −1) to avoid infinite loops
  • Store parent[v] to rebuild the path

Depth-First Search (DFS) — go deep, then backtrack

Uses recursion (or an explicit stack).

  • Connected components, cycle detection, topological sort (task/course ordering), maze solving, finding paths

Complexity

Both BFS and DFS: O(V + E) with adjacency lists.

Beyond BFS/DFS

  • Dijkstra (priority_queue): shortest paths with non-negative weights
  • Topological sort (DFS or Kahn's algorithm with in-degrees)
  • Union-Find: connectivity, Kruskal's minimum spanning tree
  • A*: pathfinding in games and maps

Example

C++
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <vector>

using Graph = std::vector<std::vector<int>>;

std::vector<int> bfs_path(const Graph& g, int start, int goal) {
    std::vector<int> parent(g.size(), -1);
    std::vector<bool> seen(g.size(), false);
    std::queue<int> q;
    q.push(start);
    seen[start] = true;
    while (!q.empty()) {
        int u = q.front(); q.pop();
        if (u == goal) break;
        for (int v : g[u])
            if (!seen[v]) { seen[v] = true; parent[v] = u; q.push(v); }
    }
    if (!seen[goal]) return {};
    std::vector<int> path;
    for (int v = goal; v != -1; v = parent[v]) path.push_back(v);
    std::reverse(path.begin(), path.end());
    return path;
}

void dfs(const Graph& g, int u, std::vector<int>& component, std::vector<bool>& seen) {
    seen[u] = true;
    component.push_back(u);
    for (int v : g[u]) if (!seen[v]) dfs(g, v, component, seen);
}

bool topo_visit(const Graph& g, int u, std::vector<int>& state, std::vector<int>& order) {   // 0 new, 1 active, 2 done
    state[u] = 1;
    for (int v : g[u]) {
        if (state[v] == 1) return false;                         // back edge: cycle
        if (state[v] == 0 && !topo_visit(g, v, state, order)) return false;
    }
    state[u] = 2;
    order.push_back(u);
    return true;
}

int main() {
    std::vector<std::string> city = { "Kathmandu", "Pokhara", "Chitwan", "Lumbini", "Butwal", "Ilam", "Jhapa" };
    Graph roads(city.size());
    auto road = [&](int a, int b) { roads[a].push_back(b); roads[b].push_back(a); };
    road(0, 1); road(0, 2); road(1, 4); road(2, 4); road(4, 3); road(5, 6);   // Ilam-Jhapa are separate

    auto path = bfs_path(roads, 0, 3);
    std::cout << "fewest stops Kathmandu -> Lumbini:";
    for (int v : path) std::cout << ' ' << city[v];
    std::cout << " (" << path.size() - 1 << " roads)\n";
    std::cout << "path Kathmandu -> Ilam found? " << std::boolalpha << !bfs_path(roads, 0, 5).empty() << '\n';

    std::vector<bool> seen(city.size(), false);
    int comp_no = 0;
    for (int u = 0; u < static_cast<int>(city.size()); ++u) {
        if (seen[u]) continue;
        std::vector<int> comp;
        dfs(roads, u, comp, seen);
        std::cout << "region " << ++comp_no << ':';
        for (int v : comp) std::cout << ' ' << city[v];
        std::cout << '\n';
    }

    std::vector<std::string> course = { "Basics", "Pointers", "Classes", "Templates", "STL" };
    Graph prereq(course.size());                                  // edge a -> b: a before b
    prereq[0] = { 1, 2 }; prereq[1] = { 2 }; prereq[2] = { 3 }; prereq[3] = { 4 };
    std::vector<int> state(course.size(), 0), order;
    for (int u = 0; u < static_cast<int>(course.size()); ++u)
        if (state[u] == 0) topo_visit(prereq, u, state, order);
    std::reverse(order.begin(), order.end());
    std::cout << "study order:";
    for (int v : order) std::cout << ' ' << course[v];
    std::cout << '\n';
    return 0;
}

/* Output:
fewest stops Kathmandu -> Lumbini: Kathmandu Pokhara Butwal Lumbini (3 roads)
path Kathmandu -> Ilam found? false
region 1: Kathmandu Pokhara Butwal Chitwan Lumbini
region 2: Ilam Jhapa
study order: Basics Pointers Classes Templates STL
*/