aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/old/examples/bfs.v
diff options
context:
space:
mode:
authorIndrajith K L2022-12-03 17:00:20 +0530
committerIndrajith K L2022-12-03 17:00:20 +0530
commitf5c4671bfbad96bf346bd7e9a21fc4317b4959df (patch)
tree2764fc62da58f2ba8da7ed341643fc359873142f /v_windows/v/old/examples/bfs.v
downloadcli-tools-windows-master.tar.gz
cli-tools-windows-master.tar.bz2
cli-tools-windows-master.zip
Adds most of the toolsHEADmaster
Diffstat (limited to 'v_windows/v/old/examples/bfs.v')
-rw-r--r--v_windows/v/old/examples/bfs.v41
1 files changed, 41 insertions, 0 deletions
diff --git a/v_windows/v/old/examples/bfs.v b/v_windows/v/old/examples/bfs.v
new file mode 100644
index 0000000..b92763e
--- /dev/null
+++ b/v_windows/v/old/examples/bfs.v
@@ -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']
+}