#include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<(int)(n);i++)

int n,c;
int mp[525][525];
int d[35][35];
int sum[3][35];

int main(){
  scanf("%d%d", &n,&c);
  REP(i,c)REP(j,c)scanf("%d",&d[i][j]);
  REP(i,n)REP(j,n)scanf("%d",&mp[i][j]);
  REP(i,n)REP(j,n)mp[i][j]--;
  REP(col,c)REP(i,n)REP(j,n)sum[(i+j)%3][col] += d[mp[i][j]][col];
  int ans = 1<<30;
  REP(x,c)REP(y,c)REP(z,c)if(x!=y && y!=z && z!=x){
    ans = min(ans, sum[0][x] + sum[1][y] + sum[2][z]);
  }
  printf("%d\n", ans);
  return 0;
}
