v / examples / graphs / bfs.v
41 lines · 40 sloc · 991 bytes · 3c5cfa22d1c364b27334cf696ca7461be68fb10d
Raw
1fn main() {
2 graph := {
3 'A': ['B', 'C']
4 'B': ['A', 'D', 'E']
5 'C': ['A', 'F']
6 'D': ['B']
7 'E': ['B', 'F']
8 'F': ['C', 'E']
9 }
10 println('Graph: ${graph}')
11 path := breadth_first_search_path(graph, 'A', 'F')
12 println('The shortest path from node A to node F is: ${path}')
13 assert path == ['A', 'C', 'F']
14}
15
16// Breadth-First Search (BFS) allows you to find the shortest distance between two nodes in the graph.
17fn breadth_first_search_path(graph map[string][]string, vertex string, target string) []string {
18 mut path := []string{}
19 mut visited := []string{len: 6, init: vertex}
20 mut queue := [][][]string{}
21 queue << [[vertex], path]
22 for queue.len > 0 {
23 mut idx := queue.len - 1
24 node := queue[idx][0][0]
25 path = queue[idx][1]
26 queue.delete(idx)
27 if node == target {
28 path << node
29 return path
30 }
31 for child in graph[node] {
32 mut tmp := path.clone()
33 if child !in visited {
34 visited << child
35 tmp << node
36 queue << [[child], tmp]
37 }
38 }
39 }
40 return path
41}
42