(********************************************************************)
(*  OCaml code from the book ``Learn Programming with OCaml''       *)
(*  See https://usr.lmf.cnrs.fr/lpo/                                *)
(*                                                                  *)
(*  Sylvain Conchon and Jean-Christophe Filliâtre                   *)
(*  Copyright 2025 Université Paris-Saclay and CNRS                 *)
(*                                                                  *)
(*  Openly licensed via CC BY SA 4.0                                *)
(*  See https://creativecommons.org/licenses/by-sa/4.0/deed.en      *)
(********************************************************************)

(* Program 102 on page 427
   The Bellman-Ford algorithm *)

  let iter_edge f g =
    iter_vertex (fun u ->
      iter_succ (fun v -> f u v (weight g u v)) g u) g

  exception NegativeCycle

  let bellman_ford g s =
    let h = H.create () in
    iter_vertex (fun v -> H.add h v max_float) g;
    H.add h s 0.;
    for i = 1 to nb_vertex g - 1 do
      iter_edge (fun u v w ->
        let d = H.find h u +. w in
        if d < H.find h v then H.replace h v d
      ) g
    done;
    iter_edge (fun u v w ->
      if H.find h u +. w < H.find h v then
        raise NegativeCycle
    ) g;
    h

This document was generated using caml2html