open Scanf
open Printf

let id a = a
let pair a b = a, b
let triplet a b c = a, b, c

let rec scan_list = function
  | 1 -> scanf "%d" (fun k -> [k])
  | n -> scanf "%d " (fun k -> k :: scan_list (n-1))

let scan_matrix n m = let arr = Array.make_matrix n m 0 in
  for i = 1 to n do
    for j = 1 to m do begin
      if i = n && j = m
      then scanf "%d " (fun k -> arr.(i-1).(j-1) <- k)
      else scanf "%d " (fun k -> arr.(i-1).(j-1) <- k)
    end
    done
  done; arr

let f cs = let cn = Array.length cs in
  let c0 = ref [] in
  let c1 = ref [] in
  let c2 = ref [] in
  for i = 1 to cn do
    for j = 1 to cn do
      match (i+j) mod 3 with
      | 0 -> c0 := cs.(i-1).(j-1) :: !c0
      | 1 -> c1 := cs.(i-1).(j-1) :: !c1
      | 2 -> c2 := cs.(i-1).(j-1) :: !c2
      | _ -> failwith ""
    done
  done; (!c0, !c1, !c2)

let rec seq start end_ = if start = end_
  then [end_]
  else start :: seq (start+1) end_

let rec zip3 x0 y0 z0 = match x0, y0, z0 with
  | [], _, _ -> []
  | (x::xs), (y::ys), (z::zs) -> (x,y,z) :: zip3 xs ys zs

let cost ds new_c cs = List.fold_left (+) 0 @@ List.map (fun c -> ds.(c-1).(new_c-1)) cs

let costs ds cs = List.map (fun k -> cost ds k cs) (seq 1 (Array.length ds))

let min_comb ds =
  let a0 = List.sort (fun (x,_,_) (y,_,_) -> compare x y) ds in
  let a1 = List.sort (fun (_,x,_) (_,y,_) -> compare x y) (List.tl a0) in
  let a2 = List.sort (fun (_,_,x) (_,_,y) -> compare x y) (List.tl a1) in
  match List.hd a0, List.hd a1, List.hd a2 with
  | (x,_,_), (_,y,_), (_,_,z) -> x+y+z

let fold_left1 f lst = List.fold_left f (List.hd lst) (List.tl lst)

let () = let n,c = scanf "%d %d\n" pair in
  let ds = scan_matrix c c in
  let cs = scan_matrix n n in
  let c0,c1,c2 = f cs in
  let d0,d1,d2 = costs ds c0, costs ds c1, costs ds c2 in
  let ans = fold_left1 min @@ List.map min_comb
      [zip3 d0 d1 d2;
       zip3 d0 d2 d1;
       zip3 d1 d0 d2;
       zip3 d1 d2 d0;
       zip3 d2 d0 d1;
       zip3 d2 d1 d0]
  in printf "%d\n" ans