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

    let calc c1 c2 c3 =
        let c4 = [| c1; c2; c3 |] in
        let rec loop_y y acc =
            let rec loop_x x acc =
                if x = n then acc else
                    let acc = acc + d.(cc.(y).(x) - 1).(c4.((x + y) mod 3)) in
                    loop_x (x + 1) acc
            in
            if y = n then acc else loop_y (y + 1) (loop_x 0 acc)
        in
        loop_y 0 0
    in

    let rec loop_c1 c1 acc =
        let rec loop_c2 c2 acc =
            let rec loop_c3 c3 acc =
                if c3 = c then acc else
                    let acc = if c3 = c1 || c3 = c2 then acc else
                                min acc (calc c1 c2 c3)
                    in
                    loop_c3 (c3 + 1) acc
            in
            if c2 = c then acc else
                let acc = if c2 = c1 then acc else loop_c3 0 acc in
                loop_c2 (c2 + 1) acc
        in
        if c1 = c then acc else loop_c1 (c1 + 1) (loop_c2 0 acc)
    in
    loop_c1 0 max_int |> Printf.printf "%d\n"
)