#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define rep(i,s,e) for(int (i) = (s);(i) <= (e);(i)++)

int D[33][33];
int c[505][505];


int sum[3][505];

int main(){
  int N,C;
  cin >> N >> C;
  for(int i = 0;i < C;i++){
    for(int j = 0;j < C;j++){
      cin >> D[i][j];
    }
  }

  for(int i = 0;i < N;i++){
    for(int j = 0;j < N;j++){
      cin >> c[i][j];
      c[i][j]--;
    }
  }

  for(int i = 0;i < N;i++){
    for(int j = 0;j < N;j++){
      for(int to = 0;to < C;to++){
        sum[(i + 1 + j + 1) % 3][to] += D[c[i][j]][to];
      }
    }
  }
  int ans = 1e9;
  rep(i,0,C - 1)rep(j,0,C - 1)rep(k,0,C - 1){
    if(i == j || j == k || k == i) continue;
    ans = min(ans , sum[0][i] + sum[1][j] + sum[2][k]);
  }
  cout << ans << endl;
}
