#include <bits/stdc++.h>

using namespace std;

int n, C, d[31][31], c[3][31], ans = 0x3f3f3f3f;
bool used[31];

void search(int x, int y)
{
    if (x > 2) { ans = min(ans, y); return; }
    int sum = 0;
    for (int i = 1; i <= C; i++)
    {
        if (used[i]) continue;
        sum = 0;
        for (int j = 1; j <= C; j++) sum += c[x][j] * d[j][i];
        used[i] = true;
        search(x + 1, y + sum);
        used[i] = false;
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin >> n >> C;
    for (int i = 1; i <= C; i++)
        for (int j = 1; j <= C; j++) cin >> d[i][j];
    int t;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++) { cin >> t; c[(i + j) % 3][t]++; }
    search(0, 0);
    cout << ans << endl;
    return 0;
}