#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(), (x).end()
#define INF 1000000000

int N, C, D[35][35], cost[3][35];

int main() {
  vector<int> id[3];
  cin >> N >> C;

  rep(i, C) {
    rep(j, C) {
      cin >> D[i][j];
    }
  }

  rep(i, N) {
    rep(j, N) {
      int tmp;
      cin >> tmp;
      id[(i + j) % 3].push_back(tmp-1);
    }
  }

  rep(i, C) {
    rep(j, 3) {
      for (int& elem : id[j]) {
        cost[j][i] += D[elem][i];
      }
    }
  }

  int ans = INF;
  rep(i, C) {
    rep(j, C) {
      if (i == j) continue;
      rep(k, C) {
        if (k == i || k == j) continue;
        ans = min(ans, cost[0][i]+cost[1][j]+cost[2][k]);
      }
    }
  }

  cout << ans << endl;

  return 0;

}