let () =
  let n, c = Scanf.scanf "%d %d " (fun a b -> a, b) in
  let d_mat = Array.init c (fun _ ->
      Array.init c (fun _ -> Scanf.scanf "%d " (fun a -> a))
    ) in
  let c_mat = Array.init n (fun _ ->
      Array.init n (fun _ -> Scanf.scanf "%d " (fun a -> a-1))
    ) in

  let diag_d = Array.make_matrix (3) c 0 in

  for i=0 to n-1 do
    for j=0 to n-1 do
      let cij = c_mat.(i).(j) in
      for k=0 to c-1 do
        let d = d_mat.(cij).(k) in
        let diag = (i+j) mod 3 in
        diag_d.(diag).(k) <- d+ diag_d.(diag).(k);
      done;
    done;
  done;

  let res = ref max_int in
  for c1 = 0 to c-1 do
    for c2 = 0 to c-1 do
      for c3 = 0 to c-1 do
        if c1 = c2 || c2 = c3 || c3 = c1 then
          ()
        else (
          let tmp = diag_d.(0).(c1) + diag_d.(1).(c2) + diag_d.(2).(c3) in
          if !res > tmp then res := tmp else ();
        )
      done;
    done;
  done;

  Printf.printf "%d\n" !res

