Typorithm · medium

Depth-First Search

▷ Interactive algorithm labdepth-first-searchsearchgraphstacktraversal
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Depth-First Search

0%

Search Algorithms

Depth-First Search explores a graph by going deep along one path before backtracking.

DFS uses a stack to choose the most recently discovered node.

It can be implemented recursively or iteratively; this lesson uses a stack.

A visited set prevents cycles from causing repeated work.

DFS is useful for reachability, connected components, and backtracking-style exploration.

Preparing algorithm lab…
01

Use a stack.

02

Pop the newest node.

03

Skip already visited nodes.

04

Push neighbors to go deeper.

05

Time is O(V + E).

function depthFirstSearch(graph, start, target) {
  const stack = [start];
  const visited = new Set();

  while (stack.length > 0) {
    const node = stack.pop();

    if (visited.has(node)) continue;
    visited.add(node);

    if (node === target) return true;

    for (const neighbor of graph[node] ?? []) {
      stack.push(neighbor);
    }
  }

  return false;
}

Read the implementation

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

1. Stack

DFS uses a stack to explore the most recent node first.

const stack = [start]

2. Visited set

visited prevents repeated processing.

const visited = new Set()

3. Stack loop

Keep going while there are nodes to explore.

while (stack.length > 0)

4. Pop node

Take the newest discovered node.

const node = stack.pop()

5. Skip visited

Avoid processing a node twice.

if (visited.has(node)) continue

6. Target check

Return true when DFS reaches the target.

if (node === target) return true

7. Push neighbor

Neighbors are pushed for later depth-first exploration.

stack.push(neighbor)

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.

Depth-First Search: Visual Walkthrough & Practice · Typorithm | ApplyDjinn