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
}Report a problem with this exampleOpens a pre-filled issue on GitHub.