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;

void main() {
    int n, c;
    scan(n, c);
    auto d = new int[][](c, c);
    foreach (i ; 0 .. c) {
        d[i] = readln.split.to!(int[]);
    }
    auto cnt = new int[][](3, c);
    foreach (i ; 0 .. n) {
        auto line = readln.split.map!(x => x.to!int - 1).array;
        foreach (j, cij; line) {
            cnt[(i + j) % 3][cij]++;
        }
    }

    debug {
        writeln(cnt);
    }



    int ans = 10^^9 + 3;

    int check(int x, int y, int z) {
        int res;

        foreach (i ; 0 .. 3) {
            foreach (j ; 0 .. c) {
                if (i == 0) {
                    res += d[j][x] * cnt[i][j];
                }
                else if (i == 1) {
                    res += d[j][y] * cnt[i][j];
                }
                else {
                    res += d[j][z] * cnt[i][j];
                }
            }
        }

        debug {
            writefln("(x,y,z) = (%d, %d, %d)", x, y, z);
            writefln("iwa %d", res);
        }

        return res;
    }

    foreach (x ; 0 .. c) {
        foreach (y ; 0 .. c) {
            foreach (z ; 0 .. c) {
                if (x == y || y == z || x == z) {
                    continue;
                }
                ans = min(ans, check(x, y, z));
            }
        }
    }

    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);
        }
    }
}
