Created
September 20, 2023 14:01
-
-
Save orhanerday/be655ca600659f00d475fdbf9e78d55b to your computer and use it in GitHub Desktop.
Golang BFS algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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