#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3f
#define EPS (1e-10)
using namespace std;
typedef long long ll;
typedef pair<int,int>P;

int d[100][100],c[1000][1000];
int cnt[3][50];

signed main(){
	int n,c;scanf("%d%d",&n,&c);
	rep(i,c)rep(j,c)cin>>d[i][j];
	rep(i,n)rep(j,n)cin>>::c[i][j],::c[i][j]--;
	rep(i,n)rep(j,n){
		//~ t[(i+j+2)%3]++;
		cnt[(i+j+2)%3][::c[i][j]]++;
	}
	int Min=INT_MAX;
	rep(i,c)rep(j,c){
		if(i==j)continue;
		rep(k,c){
			if(i==k||j==k)continue;
			int a[]{i,j,k};
			int cnt=0;
			rep(t,3){
				rep(l,c){
					cnt+=d[l][a[t]]*::cnt[t][l];
				}
			}
			Min=min(Min,cnt);
		}
	}
	cout<<Min<<endl;
}