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] (space-separated). Calls unwind 6 -> 5 -> 4 -> 3 -> 2 -> 1 after all vertices are visited.

Basic Implementation

basic.go
package main

import "fmt"

var adj = map[int][]int{
	1: {2, 3},
	2: {1, 4},
	3: {1, 4},
	4: {2, 3, 5},
	5: {4, 6},
	6: {5},
}
var visited = map[int]bool{}
var order = []int{}

func dfs(v int) {
	visited[v] = true
	order = append(order, v)
	for _, nb := range adj[v] {
		if !visited[nb] {
			dfs(nb)
		}
	}
}

func main() {
	dfs(1)
	fmt.Println(order)
}

Complexity

  • Time: O(V + E)
  • Space: O(V) recursion depth

Implementation notes

  • Go: a recursive dfs over package-level adj, visited, and order; fmt.Println prints a slice space-separated.
  • The replay shows the current vertex, the visited set, and the running visit order after each entry, matching the lesson spec.
recursive descent Follow one branch to its end, then unwind and try the next neighbour.