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
  (seq 0 (c-1) >>= fun i ->
   seq 0 (c-1) >>= fun j ->
   seq 0 (c-1) >>= fun k ->
     if i = j || j = k || k = i then []
     else [
       let t = [|i; j; k;|] in
       (seq 0 (n-1) >>= fun x ->
        seq 0 (n-1) >>= fun y ->
          [d.(b.(x).(y)-1).(t.((x+y) mod 3))])
       |> List.fold_left (+) 0
     ])
  |> List.fold_left min 10101010101010 
  |> Printf.printf "%d\n"