Skip to main content
๐Ÿ“œ WAYPOINT LESSON

BFS, DFS, and Components

โญ beginnerโณ 17 min read๐Ÿ“ Lesson 47 of 281

BFS = shortest unweighted paths via a queue; DFS = deep exploration via recursion or a stack; both mark visited ON enqueue/push.

BFS โ€” level by level

vector<int> dist(n + 1, -1);
queue<int> q;
dist[s] = 0; q.push(s);          // mark AT PUSH, not at pop
while (!q.empty()) {
    int u = q.front(); q.pop();
    for (int v : adj[u])
        if (dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); }
}

dist[v] is the exact shortest edge-count from s. The classic bug: marking visited at pop โ€” the same vertex enters the queue many times, memory and time blow up on dense graphs.

DFS โ€” the same graph, different order

Recursive form is shortest to write; depth can hit V, so V = 10^5 needs the explicit-stack form (or a bigger stack โ€” not portable):

vector<int> st;
vis[s] = true; st.push_back(s);   // mark AT PUSH here too
while (!st.empty()) {
    int u = st.back(); st.pop_back();
    for (int v : adj[u])
        if (!vis[v]) { vis[v] = true; st.push_back(v); }
}

Connected components

Loop all vertices; each unvisited vertex starts one traversal, and that traversal marks exactly its component:

int comps = 0;
for (int v = 1; v <= n; ++v)
    if (!vis[v]) { ++comps; /* traverse from v */ }

Grids are graphs

Each open cell is a vertex; neighbors are the up/down/left/right open cells. Flood fill = BFS/DFS on that implicit graph โ€” the same visited discipline, coordinates instead of indices.

โšก Now practice

Ready to Code
Graph Theory Problem SetComponents, BFS distances, flood fill, maze escape, and tree checking.
5 challenges ยท ยท ~50 min