#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
typedef long long ll;
int main(){
    int n,C,D[30][30],c[500][500];
    ll ans[3][30]={0},m=1e18;
    cin>>n>>C;
    rep(i,C)rep(j,C) cin>>D[i][j];
    rep(i,n)rep(j,n) cin>>c[i][j];
    rep(i,3){
        rep(j,C){
            rep(k,n)rep(l,n)if((k+l)%3==i) ans[i][j]+=D[c[k][l]-1][j];
        }
    }
    rep(i,C)rep(j,C)rep(k,C)if(i!=j&&j!=k&&k!=i) m=min(m,ans[0][i]+ans[1][j]+ans[2][k]);
    cout<<m;
}