DSAVisualiseData Structures & Algorithms Studio
Graphs & Connectivity Hard

Depth-First Path Search

Recursive depth-first search stores the parent of each discovered vertex, then follows those parent links to reconstruct a path.

Trace input

Bounded JSON

Edit the lesson input, then build a deterministic source-linked trace.

This lesson validates its own input and operation limits.

Source scenarios

Complexity

BestO(V + E) preprocessing and O(L) path reconstruction
AverageO(V + E) preprocessing and O(L) path reconstruction
WorstO(V + E) preprocessing and O(L) path reconstruction
SpaceO(V + E) graph storage and up to O(V) recursive stack

Array state

Follow the active comparisons and writes.

Live snapshot

Current operation

Trace state
Ready to explore
Source behavior & common mistakes

From a source vertex in an undirected graph, determine whether the target is reachable and return the source-to-target DFS path, or null when no path exists.

  • DFS uses adjacency-list insertion order, so the returned path depends on the order edges were added.
  • The DFS path is not necessarily a shortest path.
  • Set edgeTo[w] before recursing so each discovered child can later walk back to the source.
  • pathTo pushes vertices from target back to source, and returning Stack directly exposes that same target-to-source insertion order through its Iterable interface.
  • An unreachable target makes hasPathTo return false and pathTo return null; edgeTo's default zero values do not imply reachability.
  • The source expects valid vertex indices; input is checked and bounded to 20 vertices and 48 edges for safe recursion and finite traces.

Algorithm code

Java
DepthFirstPaths.javaStep linked
The highlighted line follows the current step.

Ready to begin

Press Play to see what happens.

Detailed execution
Snapshot 1 / 1