#include<cstdio>
#include<iostream>
using namespace std;
int n, c, num[5][1005], C[1005][1005], d[1005][1005];
int calc (int x, int y, int z) {
	int sum = 0;
	for (int j = 1; j <= c; j++)
		sum += d[j][x] * num[0][j] + d[j][y] * num[1][j] + d[j][z] * num[2][j];
	return sum;
}
int main() {
	cin >> n >> c;
	for (int i = 1; i <= c; i++)
		for (int j = 1; j <= c; j++)
			cin >> d[i][j];
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++) {
			cin >> C[i][j];
			num[ (i + j) % 3][C[i][j]]++;
		}
	int ans = 0x7fffffff;
	for (int i = 1; i <= c; i++)
		for (int j = 1; j <= c; j++)
			for (int k = 1; k <= c; k++) {
				if (i == j || k == j || i == k) continue;
				ans = min (ans, calc (i, j, k));
			}
	cout << ans << endl;
}