Files
rose-ash/lib/ocaml/baseline/min_cost_path.ml
giles c69a7694c8
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 22s
ocaml: phase 5.1 min_cost_path.ml baseline (4x4 grid DP, optimal cost 12)
Standard 2D DP for min-cost path with right/down moves only:

  dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + cost[i][j]

  cost:                  dp:
    1 3 1 2                1  4  5  7
    1 5 1 3                2  7  6  9
    4 2 1 4                6  8  7 11
    1 6 2 3                7 13  9 12

Optimal cost from (0,0) to (3,3) = 12.

Tests nested 2D arrays via Array.init + Array.make, double-nested
for-loops with branched edges (first row, first column, general),
mixed .(i-1).(j) read + .(i).(j)<- write on the same DP array.

161 baseline programs total.
2026-05-10 22:37:44 +00:00

32 lines
618 B
OCaml

let h = 4
let w = 4
let cost = [|
[| 1; 3; 1; 2 |];
[| 1; 5; 1; 3 |];
[| 4; 2; 1; 4 |];
[| 1; 6; 2; 3 |]
|]
let min_cost_path () =
let dp = Array.init h (fun _ -> Array.make w 0) in
dp.(0).(0) <- cost.(0).(0);
for j = 1 to w - 1 do
dp.(0).(j) <- dp.(0).(j - 1) + cost.(0).(j)
done;
for i = 1 to h - 1 do
dp.(i).(0) <- dp.(i - 1).(0) + cost.(i).(0)
done;
for i = 1 to h - 1 do
for j = 1 to w - 1 do
let a = dp.(i - 1).(j) in
let b = dp.(i).(j - 1) in
dp.(i).(j) <- (if a < b then a else b) + cost.(i).(j)
done
done;
dp.(h - 1).(w - 1)
;;
min_cost_path ()