2022-04-22 12:01:29 +03:00
|
|
|
fn main() {
|
|
|
|
graph := {
|
|
|
|
'A': ['B', 'C']
|
|
|
|
'B': ['A', 'D', 'E']
|
|
|
|
'C': ['A', 'F']
|
|
|
|
'D': ['B']
|
|
|
|
'E': ['B', 'F']
|
|
|
|
'F': ['C', 'E']
|
|
|
|
}
|
2022-11-15 16:53:13 +03:00
|
|
|
println('Graph: ${graph}')
|
2022-04-22 12:01:29 +03:00
|
|
|
path := breadth_first_search_path(graph, 'A', 'F')
|
2022-11-15 16:53:13 +03:00
|
|
|
println('The shortest path from node A to node F is: ${path}')
|
2022-04-22 12:01:29 +03:00
|
|
|
assert path == ['A', 'C', 'F']
|
|
|
|
}
|
|
|
|
|
2021-05-05 21:52:28 +03:00
|
|
|
// 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{}
|
2022-12-21 22:24:16 +03:00
|
|
|
mut visited := []string{len: 6, init: vertex}
|
2021-05-05 21:52:28 +03:00
|
|
|
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
|
|
|
|
}
|