(* 与えられたリストからk要素を選ぶ順列 *)
let perm k xs =
  let rec perm_aux trace n k i xs ys acc =
    match k, i, xs with
    | 0, _, _ -> trace :: acc
    | _, 0, _ -> acc
    | _, _, [] -> perm_aux trace n k i (List.rev ys) [] acc
    | _, _, x :: xs ->
        perm_aux trace n k (i - 1) xs (x :: ys) @@
        perm_aux (x :: trace) (n - 1) (k - 1) (n - 1) xs ys acc in
  let n = List.length xs in
  perm_aux [] n k n xs [] []

let () = Scanf.scanf "%d %d\n" @@ fun n c ->
  let dss =
    Array.init c @@ fun _ ->
      Array.init c @@ fun _ ->
        Scanf.scanf "%d " @@ fun d -> d in
  let css =
    Array.init n @@ fun _ ->
      Array.init n @@ fun _ ->
        Scanf.scanf "%d " @@ fun c -> c in
  let colours = Array.make_matrix 3 c 0 in
  Array.iteri (fun i ->
    Array.iteri (fun j c ->
      colours.((i + j + 2) mod 3).(c - 1) <- colours.((i + j + 2) mod 3).(c - 1) + 1)) css;
  Array.init c (fun c -> c)
  |> Array.to_list
  |> perm 3
  |> List.map (List.mapi (fun m y ->
      Array.mapi (fun x n -> n * dss.(x).(y)) colours.(m)
      |> Array.fold_left ( + ) 0))
  |> List.map (List.fold_left ( + ) 0)
  |> List.fold_left min max_int
  |> Printf.printf "%d\n"

