Traverse graphs and compute shortest paths
Traverse graphs and compute shortest paths
A graph contains vertices and edges. An adjacency list stores each vertex’s neighbors. Depth-first search (DFS) explores one branch before returning; breadth-first search (BFS) explores by increasing edge distance from a start vertex. Mark visited vertices to avoid repeating work or looping on cycles. BFS gives shortest distances when every edge has equal unit cost.
package main
import ( "fmt")
func dfs(g [][]int, v int, seen []bool) { if seen[v] { return } seen[v] = true fmt.Print(v, " ") for _, u := range g[v] { dfs(g, u, seen) }}func main() { g := [][]int{{1, 2}, {2}, {0}, nil} dfs(g, 0, make([]bool, len(g))) fmt.Println()}Vertices are numbered 0 through len(g)-1; all neighbors and the start must be valid indices. Mark before recursing, so the 2→0 cycle terminates. Vertex 3 is unreachable. The traversal order follows the supplied neighbor order. O(V+E) time and O(V) auxiliary space including the stack for a full reachable traversal.
Expected output:
0 1 2Compute unweighted shortest distances
package main
import ( "fmt")
func bfs(g [][]int, start int) []int { d := make([]int, len(g)) for i := range d { d[i] = -1 } d[start] = 0 q := []int{start} for head := 0; head < len(q); head++ { v := q[head] for _, u := range g[v] { if d[u] < 0 { d[u] = d[v] + 1 q = append(q, u) } } } return d}func main() { g := [][]int{{1, 2}, {3}, {3}, {0}, nil} fmt.Println(bfs(g, 0))}The queue uses a head index instead of shifting elements. Mark distance at enqueue time, ensuring each vertex enters once. The first discovery has minimum edge count because the queue processes layers in order. Time O(V+E), space O(V). For nonnegative unequal weights use an appropriate algorithm such as Dijkstra, not ordinary BFS. Validate indices before processing external graph input.
Expected output:
[0 1 1 2 -1]Try it locally
Use BFS to compute distances from 0 in graph {{1},{2,3},{},{},{}}. Print distances; vertex 4 is unreachable.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Algorithms 09: Traverse graphs and compute shortest paths
Check the lesson objective before moving on.
When does ordinary BFS compute shortest distances?
When should a BFS vertex be marked visited?