Graphs
Depth-First Search (Recursive)
Visit a start vertex, then recurse into its first unvisited neighbour all
the way down before backtracking. A visited set prevents revisiting, and
neighbour insertion order fixes the visit sequence.
Algorithm
On the canonical 6-vertex graph from graph-adjacency-list, starting at
vertex 1, the deterministic visit order is [1, 2, 4, 3, 5, 6]. Calls
unwind 6 -> 5 -> 4 -> 3 -> 2 -> 1 after all vertices are visited.
recursive descent
Follow one branch to its end, then unwind and try the next neighbour.
Visual walkthrough
Basic Implementation
Basic.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Basic {
static Map<Integer, List<Integer>> adj = new LinkedHashMap<>();
static Set<Integer> visited = new LinkedHashSet<>();
static List<Integer> order = new ArrayList<>();
static void dfs(int v) {
visited.add(v);
order.add(v);
for (int nb : adj.get(v)) {
if (!visited.contains(nb)) {
dfs(nb);
}
}
}
public static void main(String[] args) {
adj.put(1, List.of(2, 3));
adj.put(2, List.of(1, 4));
adj.put(3, List.of(1, 4));
adj.put(4, List.of(2, 3, 5));
adj.put(5, List.of(4, 6));
adj.put(6, List.of(5));
dfs(1);
System.out.println(order);
}
}
Complexity
- Time: O(V + E)
- Space: O(V) recursion depth
Implementation notes
- Java: a
static dfs(int v)method shares thevisitedLinkedHashSet andorderlist; recursion depth is bounded byV. - The replay shows the current vertex, the visited set, the running visit order, and the call stack after each entry, matching the lesson spec.