ocaml: phase 5.1 bfs.ml baseline (20/20 pass)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 20s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 20s
Graph BFS using Queue + Hashtbl visited-set + List.assoc_opt + List.iter. Returns 6 for a graph where A reaches B/C/D/E/F. Demonstrates 4 stdlib modules (Queue, Hashtbl, List) cooperating in a real algorithm.
This commit is contained in:
43
lib/ocaml/baseline/bfs.ml
Normal file
43
lib/ocaml/baseline/bfs.ml
Normal file
@@ -0,0 +1,43 @@
|
||||
(* Baseline: graph BFS using Queue + Hashtbl visited set.
|
||||
Returns the count of reachable nodes. *)
|
||||
|
||||
(* Adjacency as an assoc list of (node, neighbors). *)
|
||||
let graph =
|
||||
[ ("A", ["B"; "C"])
|
||||
; ("B", ["D"])
|
||||
; ("C", ["D"; "E"])
|
||||
; ("D", ["F"])
|
||||
; ("E", ["F"])
|
||||
; ("F", [])
|
||||
]
|
||||
;;
|
||||
|
||||
let neighbors n =
|
||||
match List.assoc_opt n graph with
|
||||
| None -> []
|
||||
| Some ns -> ns
|
||||
;;
|
||||
|
||||
let bfs start =
|
||||
let visited = Hashtbl.create 16 in
|
||||
let q = Queue.create () in
|
||||
Queue.push start q ;
|
||||
Hashtbl.add visited start true ;
|
||||
let rec loop () =
|
||||
if Queue.is_empty q then ()
|
||||
else
|
||||
let v = Queue.pop q in
|
||||
List.iter
|
||||
(fun n ->
|
||||
if not (Hashtbl.mem visited n) then begin
|
||||
Hashtbl.add visited n true ;
|
||||
Queue.push n q
|
||||
end)
|
||||
(neighbors v) ;
|
||||
loop ()
|
||||
in
|
||||
loop () ;
|
||||
Hashtbl.length visited
|
||||
;;
|
||||
|
||||
bfs "A"
|
||||
@@ -1,5 +1,6 @@
|
||||
{
|
||||
"anagrams.ml": 3,
|
||||
"bfs.ml": 6,
|
||||
"btree.ml": 39,
|
||||
"calc.ml": 13,
|
||||
"closures.ml": 315,
|
||||
|
||||
Reference in New Issue
Block a user