Files
rose-ash/lib/ocaml/baseline/bipartite.ml
giles d1a4616ac4
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
ocaml: phase 5.1 bipartite.ml baseline (7-node bipartite, 4 in color 0)
BFS-based 2-coloring of an undirected graph:

  edges (undirected):
    0-1  0-3  1-2  1-4  2-5  3-4  3-6  5-6

  Partition: {0, 2, 4, 6} vs {1, 3, 5} (no odd cycles)

Returns count of color-0 vertices (4) on success, -1 on odd-cycle
detection.

Tests Queue-based BFS with a source-loop wrapper for disconnected
graphs, `1 - color.(u)` toggle, color-equality conflict check
on already-colored neighbors.

164 baseline programs total.
2026-05-10 23:08:16 +00:00

40 lines
803 B
OCaml

let is_bipartite n adj =
let color = Array.make n (-1) in
let ok = ref true in
let q = Queue.create () in
for src = 0 to n - 1 do
if color.(src) = -1 then begin
color.(src) <- 0;
Queue.push src q;
while not (Queue.is_empty q) do
let u = Queue.pop q in
List.iter (fun v ->
if color.(v) = -1 then begin
color.(v) <- 1 - color.(u);
Queue.push v q
end else if color.(v) = color.(u) then
ok := false
) adj.(u)
done
end
done;
let zeros = ref 0 in
for i = 0 to n - 1 do
if color.(i) = 0 then zeros := !zeros + 1
done;
if !ok then !zeros else -1
;;
let n = 7 in
let adj = [|
[1; 3];
[0; 2; 4];
[1; 5];
[0; 4; 6];
[1; 3];
[2; 6];
[3; 5]
|] in
is_bipartite n adj