let inf = 1010101010101010
let rec seq a b = if a >= b then [] else a :: seq (a+1) b
let (>>=) xs f = List.concat (List.map f xs)

let () =
  let n, c = Scanf.scanf "%d %d" (fun x y -> x, y) in
  let d = Array.init c (fun _ ->
    Array.init c (fun _ -> Scanf.scanf " %d" (fun x -> x))) in

  let sc = Array.init 3 (fun _ -> Array.make c 0) in

  seq 0 (n*n) |> List.iter (fun m ->
    let g = (m/n + m mod n) mod 3 in
    Scanf.scanf " %d" (fun x ->
      let col = x-1 in
      seq 0 c |> List.iter (fun i ->
        sc.(g).(i) <- sc.(g).(i) + d.(col).(i))));

  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 inf
  |> Printf.printf "%d\n"