#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=int(a);i<int(b);++i)
using namespace std;
typedef long long ll;
int INF = (1LL << 30) - 1;
int MOD = 1e9+7;
int main(){
    int N,C;
    cin >> N >> C;
    int D[C][C], Color[N][N];
    rep(i,0,C)rep(j,0,C)cin >> D[i][j];
    rep(i,0,N)rep(j,0,N){
        cin >> Color[i][j];
        Color[i][j]--;
    }
    int dif[3][C];
    rep(i,0,3)rep(j,0,C)dif[i][j] = 0;
    rep(i,0,N)rep(j,0,N){
        rep(k,0,C){
            dif[(i + j) % 3][k] += D[ Color[i][j] ][k];
        }
    }
    int mini = INF;
    rep(i,0,C)rep(j,0,C)rep(k,0,C){
        if(i == j || i == k || j == k)continue;
        mini = min(mini, dif[0][i] + dif[1][j] + dif[2][k]);
    }
    cout << mini << endl;
}