Graph Theory37 sections · 1633 units
Open in Course

The Code Template

Memorize this

Here is the standard recursive DFS template you will use constantly:

visited = [false] * (n + 1)
adj = adjacency list of the graph

function dfs(u):
    visited[u] = true
    // process u here
    for each v in adj[u]:
        if not visited[v]:
            dfs(v)

// in main:
// build adj from input
// call dfs(start_vertex)

Declare a global visited array. Write a function dfs that takes a vertex uu. Inside: mark uu visited, process uu, loop through neighbors of uu, and recurse on unvisited neighbors.

This template works for nearly every DFS problem. You will modify what happens when you process a vertex, but the structure stays the same.