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.R
adj <- list("1" = c(2, 3), "2" = c(1, 4), "3" = c(1, 4), "4" = c(2, 3, 5), "5" = c(4, 6), "6" = c(5))
visited <- list()
order <- integer(0)
dfs <- function(v) {
visited[[as.character(v)]] <<- TRUE
order[length(order) + 1] <<- v
for (nb in adj[[as.character(v)]]) {
if (is.null(visited[[as.character(nb)]])) {
dfs(nb)
}
}
}
dfs(1)
cat("[", paste(order, collapse = ", "), "]\n", sep = "")
Complexity
- Time: O(V + E)
- Space: O(V) recursion depth
Implementation notes
- R: a recursive
dfs()uses<<-to update the sharedvisitedlist andordervector. - The replay shows the current vertex, the visited set, and the running visit order after each entry, matching the lesson spec.