let rec seq a b = if a >= b then [] else a :: seq (a+1) b
let (>>=) x f = List.map f x |> List.concat
let () =
  Scanf.scanf "%d %d" @@ fun n c ->
  let d =
    Array.init c (fun i ->
      Array.init c (fun j -> Scanf.scanf " %d" ((+) 0)))
  in
  let b =
    Array.init n (fun i ->
      Array.init n (fun j -> Scanf.scanf " %d" ((+) 0)))
  in

  let sc = Array.init 3 (fun _ -> Array.make c 0) in
  let _ =
    seq 0 n >>= fun x ->
    seq 0 n >>= fun y ->
      let i = (x + y) mod 3 in
      seq 0 c |> List.iter (fun j -> sc.(i).(j) <- sc.(i).(j) + d.(b.(x).(y)-1).(j));
      []
  in

  (seq 0 c >>= fun i ->
   seq 0 c >>= fun j ->
   seq 0 c >>= fun k ->
     if i = j || j = k || k = i then []
     else [ sc.(0).(i) + sc.(1).(j) + sc.(2).(k) ])
  |> List.fold_left min 10101010101010 
  |> Printf.printf "%d\n"