#include <cstdio>
#define REP(i,n) for (int i = 0; i < n ; ++i)

int N, C, X, D[30][30], t[3][30];
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", &X), t[(i+j)%3][X-1]++;
  int res = 1<<30;
  REP(i,C) REP(j,C) if(i!=j) REP(k,C) if(i!=k&&j!=k) {
    int tt = 0;
    REP(l,C) tt += D[l][i] * t[0][l];
    REP(l,C) tt += D[l][j] * t[1][l];
    REP(l,C) tt += D[l][k] * t[2][l];
    if (tt<res) res = tt;
  }
  printf("%d\n", res);
}