examples: add a BFS example for finding the shortest distance between nodes in a graph (#10006)

pull/10016/head weekly.2021.18
Vice Versa 2021-05-05 21:52:28 +03:00 committed by GitHub
parent 7288f12847
commit 4e6a19b0e5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 41 additions and 0 deletions

41
examples/bfs.v 100644
View File

@ -0,0 +1,41 @@
// Breadth-First Search (BFS) allows you to find the shortest distance between two nodes in the graph.
fn breadth_first_search_path(graph map[string][]string, vertex string, target string) []string {
mut path := []string{}
mut visited := []string{init: vertex}
mut queue := [][][]string{}
queue << [[vertex], path]
for queue.len > 0 {
mut idx := queue.len - 1
node := queue[idx][0][0]
path = queue[idx][1]
queue.delete(idx)
if node == target {
path << node
return path
}
for child in graph[node] {
mut tmp := path.clone()
if child !in visited {
visited << child
tmp << node
queue << [[child], tmp]
}
}
}
return path
}
fn main() {
graph := map{
'A': ['B', 'C']
'B': ['A', 'D', 'E']
'C': ['A', 'F']
'D': ['B']
'E': ['B', 'F']
'F': ['C', 'E']
}
println('Graph: $graph')
path := breadth_first_search_path(graph, 'A', 'F')
println('The shortest path from node A to node F is: $path')
assert path == ['A', 'C', 'F']
}