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 JSONEdit the lesson input, then build a deterministic source-linked trace.
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.
Current operation
Trace stateReady 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
JavaDepthFirstPaths.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1