DFS
Depth-first search explores a graph by going as deep as possible along one path, then backtracking. In Go you write a recursive walk or an explicit []T stack.
Detailed Explanation
BFS spreads level by level. DFS dives. You mark a node, then recurse on each unvisited neighbour (or push neighbours onto a stack). The order is not a shortest path. It is a way to visit every node, detect cycles, run topological ideas, and collect paths.
Recursive form. func walk(u int) marks u, then for _, v := range adj[u] { if !seen[v] { walk(v) } }. This is the clear form for trees and small graphs. Each pending call is a stack frame. A path of n nodes is O(n) stack. User-controlled depth (a deep comment thread, a malicious chain) should use an explicit stack.
Explicit stack. Push the start. While the stack is not empty, pop, skip if seen, mark, push neighbours. The neighbour order is reversed relative to a typical recursive walk unless you push in reverse. That rarely matters for "visit all."
Colors and cycles. For directed graphs, keep white/gray/black (or an equivalent int slice): gray means on the current path. An edge to gray is a back edge, a cycle. In an undirected graph, an edge to a seen node that is not the parent is a cycle.
Connected components. Loop for u := range adj { if !seen[u] { walk(u); comps++ } }. The same skeleton computes "can we reach t from s."
What it costs. Time O(V+E). Space O(V) for seen plus the stack or recursion. Prefer DFS when you need a path, a cycle, or a topological order of a DAG (post-order). Prefer BFS when you need unweighted distance.
Code Examples
package main
import "fmt"
func dfs(adj [][]int, start int) []int {
seen := make([]bool, len(adj))
var order []int
var walk func(u int)
walk = func(u int) {
seen[u] = true
order = append(order, u)
for _, v := range adj[u] {
if !seen[v] {
walk(v)
}
}
}
walk(start)
return order
}
func main() {
adj := [][]int{{1, 2}, {0}, {0}}
fmt.Println(dfs(adj, 0))
}func dfsIter(adj [][]int, start int) {
seen := make([]bool, len(adj))
st := []int{start}
for len(st) > 0 {
u := st[len(st)-1]
st = st[:len(st)-1]
if seen[u] {
continue
}
seen[u] = true
st = append(st, adj[u]...)
}
}Common Gotchas
Recursion on a long chain overflows the goroutine stack
switch to an explicit stack when depth is unbounded.
In undirected graphs, ignore the parent when looking for cycles
the edge you just came from is not a cycle.
Forgetting `seen` on a cyclic graph loops until crash
Forgetting `seen` on a cyclic graph loops until crash