#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#define lol(i,n) for(int i=0;i<n;i++)
#define mod 1000000007
typedef long long ll;

using namespace std;
int n,c,d[40][40],m[510][510];
int main(){
    cin>>n>>c;
    lol(i,c)lol(j,c)cin>>d[i][j];
    lol(i,n)lol(j,n)cin>>m[i][j];
    int w[3][40];
    for(int k=0;k<3;k++){
	lol(r,c){
	    w[k][r]=0;
	    lol(i,n)lol(j,n){
		if((i+j)%3==k){
		    w[k][r]+=d[m[i][j]-1][r];
		}
	    }
	}
    }
    int ans=mod;
    lol(i,c)lol(j,c)lol(k,c){
	if(i==j||i==k||j==k)continue;
	int gre=w[0][i]+w[1][j]+w[2][k];
	ans=min(ans,gre);
    }
    cout<<ans<<endl;
    return 0;
}
