let h = 6
let w = 7
let grid = [|
  [| 1; 1; 0; 0; 0; 1; 1 |];
  [| 1; 0; 0; 0; 1; 1; 0 |];
  [| 0; 0; 1; 1; 0; 0; 0 |];
  [| 0; 1; 1; 1; 0; 1; 1 |];
  [| 1; 0; 0; 0; 0; 1; 0 |];
  [| 1; 1; 0; 1; 1; 1; 0 |]
|]

let rec fill visited r c =
  if r < 0 || r >= h || c < 0 || c >= w then ()
  else if visited.(r).(c) || grid.(r).(c) = 0 then ()
  else begin
    visited.(r).(c) <- true;
    fill visited (r - 1) c;
    fill visited (r + 1) c;
    fill visited r (c - 1);
    fill visited r (c + 1)
  end

let count_islands () =
  let visited = Array.init h (fun _ -> Array.make w false) in
  let count = ref 0 in
  for r = 0 to h - 1 do
    for c = 0 to w - 1 do
      if grid.(r).(c) = 1 && not visited.(r).(c) then begin
        count := !count + 1;
        fill visited r c
      end
    done
  done;
  !count
;;

count_islands ()
