LeetCode ยท DFS

DFS Problem Set

Depth-first search is the natural tool for connected components, cycle detection, post-order dependency reasoning, and backtracking-style path exploration. If the prompt asks you to explore one branch fully before trying another, DFS should be one of your first candidates.

Related pages: DFS ยท Graph Basics ยท Topological Sort ยท Graphs
DifficultyPatternProblemKey Insight
MediumcomponentsLC 200 ยท Number of IslandsLaunch DFS from each unvisited land cell. Each launch floods exactly one connected component, so the number of launches is the answer.
Mediumcycle-detectLC 207 ยท Course ScheduleUse three-color DFS on the directed graph. Revisiting a gray node means a back edge and therefore a cycle.
MediumtopologicalLC 210 ยท Course Schedule IIDFS post-order naturally builds a topological order: push a node after exploring all of its outgoing edges, then reverse.
Mediumgraph-copyLC 133 ยท Clone GraphMemoize original โ†’ clone nodes during DFS so cycles and shared neighbors are reconstructed exactly once.
Mediumgrid-reachabilityLC 417 ยท Pacific Atlantic Water FlowReverse the thinking: DFS outward from the ocean borders. Cells reachable from both DFS passes can flow to both oceans.
Mediumpath-enumerationLC 797 ยท All Paths From Source to TargetTrack one shared path list, recurse into neighbors, and backtrack with pop. Because the graph is a DAG, no visited set is needed.
Practice note: All listed DFS problems on this page now have dedicated solution write-ups, so you can go straight from the concept page into a worked example for each major DFS pattern.

โ† Back to Graph problems