import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;

enum inf3 = 1_001_001_001;
enum inf6 = 1_001_001_001_001_001_001L;
enum mod = 1_000_000_007L;


void main() {
    int n, c;
    scan(n, c);
    auto d = iota(c).map!(i => readln.split.to!(int[])).array;
    auto ban = iota(n).map!(i => readln.split.to!(int[])).array;

    auto cnt = new int[][](3, c);
    auto z = new int[](3);

    foreach (i ; 0 .. n) {
        foreach (j ; 0 .. n) {
            cnt[(i + j) % 3][ban[i][j] - 1]++;
            z[(i + j) % 3]++;
        }
    }

    long ans = inf6;

    foreach (i ; 0 .. c) {
        foreach (j ; 0 .. c) {
            foreach (k ; 0 .. c) {
                if (i == j || j == k || i == k) continue;

                long t;

                foreach (x ; 0 .. c) {
                    t += 1L * cnt[0][x] * d[x][i];
                    t += 1L * cnt[1][x] * d[x][j];
                    t += 1L * cnt[2][x] * d[x][k];
                }

                ans = min(t, ans);
            }
        }
    }

    writeln(ans);
}









void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}

void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}
