All algorithms
Graphs

Depth-First Search (DFS)

Go as deep as possible before backtracking — the recursion tree made visible.

TimeO(V + E)SpaceO(V)CategoryGraphs

Depth-First Search dives as deep as it can along each branch before backtracking. Implemented with recursion, it naturally produces a call tree — each recursive `dfs(v)` is a child call that must finish before its parent continues.

DFS underlies cycle detection, topological sort, connected components, and bridge/articulation-point algorithms. The tricky part for learners is the backtracking: when does control return to the parent call, and what state is restored?

AlgoLens shows both the graph and the recursion tree — you see exactly how deep the current call is and when it unwinds, which is impossible to follow from `cout` alone.

The code

depth_first_search.cpp
#include <bits/stdc++.h>
using namespace std;

vector<int> adj[7];
bool visited[7];

void dfs(int u) {
    visited[u] = true;
    for (int v : adj[u]) {
        if (!visited[v]) dfs(v);
    }
}

int main() {
    int edges[6][2] = {{0,1},{0,2},{1,3},{2,4},{4,5},{3,5}};
    for (auto& e : edges) {
        adj[e[0]].push_back(e[1]);
        adj[e[1]].push_back(e[0]);
    }
    dfs(0);
    for (int i = 0; i < 6; i++) cout << visited[i] << ' ';
    cout << '\n';
    return 0;
}
Open this in the visualizer

Now run your own Depth-First Search (DFS)

AlgoLens traces your code — arrays, graphs, trees and recursion — from a real execution, so you see how it actually behaves, not a canned animation.

Paste your code

Keep going