Graph BFS Shortest Path Unweighted (Go)
Find the shortest path in an unweighted Go graph using BFS with a predecessor map for path reconstruction.
Code
package main
func bfsShortestPath(graph map[string][]string, start, end string) []string {
if start == end { return []string{start} }
queue := []string{start}
visited := map[string]bool{start: true}
parent := map[string]string{}
for len(queue) > 0 {
node := queue[0]; queue = queue[1:]
for _, neighbor := range graph[node] {
if visited[neighbor] { continue }
visited[neighbor] = true
parent[neighbor] = node
if neighbor == end {
path := []string{end}
cur := end
for { p, ok := parent[cur]; if !ok { break }; cur = p; path = append([]string{cur}, path...) }
return path
}
queue = append(queue, neighbor)
}
}
return nil
}How it works
What does the acting is the function body bfsShortestPath — everything else is wiring.
Repetition is confined to for len(queue) > 0 — the rest of the file is straight-line.
Putting it to use
The primary signature is func bfsShortestPath(graph map[string][]string, start, end string) []string
Core lines under the microscope
for { p, ok := parent[cur]; if !ok { break }; cur = p; path = append([]string{cur}, path...) }
if start == end { return []string{start} }
queue = append(queue, neighbor)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `bfsShortestPath` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.