#include <bits/stdc++.h>

using namespace std;

#define rep(i,n) for(int i=0;i<n;i++)


 long n,c;
long d[30][30];
long color[3][30];
int main(){

  cin >> n >> c;
 
 
  rep(i,c){
   rep(j,c) cin >> d[i][j];
  }
  
  rep(i,n){
   rep(j,n){
     long x;
     cin >> x;
    color[(i+j)%3][x-1]++; 
   }
  }
  
  long res=1000000000000;
  
  rep(i,c){
   rep(j,c){
   if(i==j) continue;
     rep(k,c){
      if(i==k||j==k) continue;
       long sum=0;
       rep(l,c) sum+=color[0][l]*d[l][i]+color[1][l]*d[l][j]+color[2][l]*d[l][k];
        res=min(sum,res);
     }
   }
  }

cout << res << endl;



}
