Graph Theory37 sections · 1633 units
Open in Course

The DFS Logic Flow

Step-by-Step

Here is the DFS algorithm step by step:

function dfs(u):
    visited[u] = true
    process(u)
    for each neighbor v of u:
        if not visited[v]:
            dfs(v)

Start at vertex uu. Mark uu as visited so you do not come back. Process uu (print it, add to result, whatever your problem needs). Loop through all neighbors of uu. For each neighbor vv, if vv is not visited, recursively call DFS on vv.

The recursion handles backtracking automatically. When you finish exploring all paths from vv, the recursive call returns and you continue with the next neighbor.