Typorithm · medium

Graph DFS

▷ Interactive algorithm labgraph-dfsgraph-algorithmsrecursionvisited-setdeep-first
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Graph DFS

0%

Graph Algorithms

Follow one path as deep as possible, backtracking when stuck, using a visited set against cycles.

DFS commits to a neighbor and explores it fully before trying the next one.

A visited set is essential — without it, a cycle would loop forever.

Recursion naturally implements the dive-and-backtrack behavior via the call stack.

Preparing algorithm lab…
01

Mark visited on entry.

02

Recurse into unseen neighbors.

03

The call stack does the backtracking.

function dfs(graph, start) {
  const visited = new Set();
  const order = [];

  function explore(node) {
    visited.add(node);
    order.push(node);

    for (const next of graph[node]) {
      if (!visited.has(next)) {
        explore(next);
      }
    }
  }

  explore(start);
  return order;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Visited set

Track nodes already explored to avoid infinite loops on cycles.

const visited = new Set()

2. Mark on enter

Mark a node visited as soon as exploration begins.

visited.add(node)

3. Recurse deep

Follow each unseen neighbor all the way down before backtracking.

explore(next)

4. Skip visited

Only recurse into neighbors not yet seen.

if (!visited.has(next))

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Graph DFS: Visual Walkthrough & Practice · Typorithm | ApplyDjinn