#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
#define REP(i, limit) for(int i=0; i< limit; ++i)
#define LINT long long

int main(){
  int N, C;
  cin>>N>>C;
  int D[C][C], c;
  REP(i, C){
    REP(j, C) cin>>D[i][j];
  }
  int col[3][C]; //色の個数[(i+j)%3][もとのcolor]
  int cost[3][C]; //違和感[(i+j)%3][変更後のカラー]
  REP(i, 3){
    REP(j, C){
      col[i][j]=0;
      cost[i][j]=0;
    }
  }
  REP(i, N){
    REP(j, N){
      cin>>c;
      --c;
      ++col[(i+j)%3][c];
    }
  }
  REP(i, 3){
    REP(j, C){
      REP(k, C){
        cost[i][j] += col[i][k] * D[k][j];
      }
    }
  }

  int ans=2000000000;
  REP(i, C) REP(j, C) REP(k, C){
    if(i == j ||j == k ||k == i) continue;
    ans = min(ans, cost[0][i] + cost[1][j] + cost[2][k]);
  }
  cout<<ans<<endl;


  return 0;
}
