open Big_int

let () =
    let main () =
        let h, w = Scanf.scanf "%d %d" (fun h w -> h, w) in
        let a = Array.init h (fun _ -> Array.init w (fun _ -> Scanf.scanf " %d" (fun n -> n))) in
        let b = Array.init h (fun _ -> Array.init w (fun _ -> Scanf.scanf " %d" (fun n -> n))) in
        let m = (h + w) * 80 in
        let ar = Array.make_matrix h w zero_big_int in
        let init = shift_left_big_int unit_big_int m in
        ar.(0).(0) <- shift_left_big_int unit_big_int m;
        for y = 0 to h - 1 do
            for x = 0 to w - 1 do
                let aa = abs(a.(y).(x) - b.(y).(x)) in
                if y > 0 then ar.(y).(x) <- or_big_int ar.(y).(x) ar.(y - 1).(x);
                if x > 0 then ar.(y).(x) <- or_big_int ar.(y).(x) ar.(y).(x - 1);
                ar.(y).(x) <- or_big_int (shift_left_big_int ar.(y).(x) aa) (shift_right_big_int ar.(y).(x) aa)
            done
        done;
        let rec loop i x y =
            if eq_big_int (and_big_int ar.(h - 1).(w - 1) x) zero_big_int &&
               eq_big_int (and_big_int ar.(h - 1).(w - 1) y) zero_big_int then
                   loop (i + 1) (shift_left_big_int x 1) (shift_right_big_int y 1)
            else i
        in
        let s = loop 0 init init in
        Printf.printf "%d\n" s
    in
    main ()