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.scala
import scala.collection.mutable.{HashMap, HashSet, ArrayBuffer}
object Main {
val adj = HashMap.empty[Int, List[Int]]
val visited = HashSet.empty[Int]
val order = ArrayBuffer.empty[Int]
def dfs(v: Int): Unit = {
visited += v
order += v
for (nb <- adj(v)) {
if (!visited.contains(nb)) {
dfs(nb)
}
}
}
def main(args: Array[String]): Unit = {
adj(1) = List(2, 3)
adj(2) = List(1, 4)
adj(3) = List(1, 4)
adj(4) = List(2, 3, 5)
adj(5) = List(4, 6)
adj(6) = List(5)
dfs(1)
println(order.mkString("[", ", ", "]"))
}
}
Complexity
- Time: O(V + E)
- Space: O(V) recursion depth
Implementation notes
- Scala: a recursive
dfsover object-leveladj,visited, andorder;mkStringrenders the buffer. - The replay shows the current vertex, the visited set, and the running visit order after each entry, matching the lesson spec.