#include <bits/stdc++.h>
#define REP(i, a, n) for(ll i = ((ll) a); i < ((ll) n); i++)
using namespace std;
typedef long long ll;

int main(void) {
  ll N, C;
  cin >> N >> C;
  vector< vector<ll> > D(C, vector<ll>(C)), color(N, vector<ll>(N));
  REP(i, 0, C) REP(j, 0, C) cin >> D[i][j];
  REP(i, 0, N) REP(j, 0, N) cin >> color[i][j], color[i][j]--;

  vector< vector<ll> > cnt(3, vector<ll>(C, 0));
  REP(i, 0, N) REP(j, 0, N) {
    ll p = (i + j) % 3;
    cnt[p][color[i][j]]++;
  }

  ll ans = (1LL << 60);
  REP(i, 0, C) REP(j, 0, C) REP(k, 0, C) {
    if(i == j || j == k || k == i) continue;
    ll sum = 0;
    REP(l, 0, C) {
      sum += D[l][i] * cnt[0][l];
      sum += D[l][j] * cnt[1][l];
      sum += D[l][k] * cnt[2][l];
    }
    ans = min(ans, sum);
  }
  cout << ans << endl;
}