Skip to content

Instantly share code, notes, and snippets.

@orhanerday
Created September 20, 2023 14:01
Show Gist options
  • Save orhanerday/be655ca600659f00d475fdbf9e78d55b to your computer and use it in GitHub Desktop.
Save orhanerday/be655ca600659f00d475fdbf9e78d55b to your computer and use it in GitHub Desktop.
Golang BFS algorithm
package main
import "fmt"
func main() {
graph := map[int][]int{
5: {3, 7},
3: {2, 4},
7: {8},
2: {},
4: {8},
8: {},
}
found := bfs(graph, 5)
fmt.Println(found)
}
func bfs(graph map[int][]int, vertex int) []int {
var queue []int
visited := make(map[int]bool)
visited[vertex] = true
queue = append(queue, vertex)
for len(queue) > 0 {
next := queue[0]
queue = queue[1:]
for _, neighbour := range graph[next] {
if ok := visited[neighbour]; !ok {
visited[neighbour] = true
queue = append(queue, neighbour)
}
}
}
var found []int
for i := range visited {
found = append(found, i)
}
return found
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment