Skip to content
DSA in JavaScript
← All patterns

Depth-First Search

0/18 solved

What it is

Go as deep as you can down one path, then back up and try the next. Recursion or a stack keeps track of where you came from.

Used for

Paths, connected components, cycle detection, exploring all options in trees and graphs.
791152

start at 7

Step 1 of 6

Goal: visit every node. Depth-first search picks a direction and goes as deep as it can before turning back, like exploring a maze by always taking the next corridor.

You see

  • Explore a path fully before backing up
  • Paths, depth, connected components
  • Anything recursive over a tree or graph

Learn it in

Articulation Points (or Cut Vertices)Bridges in GraphStrongly Connected ComponentEulerian PathDepth-First Search (graph)Depth-First Search (tree)Graph

Template

function dfs(node, seen = new Set()) {  if (!node || seen.has(node)) return;  seen.add(node);  for (const next of node.neighbors) dfs(next, seen);  return seen;}

Practice problems