#include <iostream>
#include <limits.h>
using namespace std;
int n, c, v;
long x;
int D[31][31] = {};
int K[3][31] = {};
int T[3][31] = {};

int main()
{
	scanf("%d %d", &n, &c);
	for (int i = 1; i <= c; ++i) {
		for (int j = 1; j <= c; ++j)
			scanf("%d", &D[i][j]);
			
	}
	for (int i = 1; i <= n; ++i) {
		for (int j = 1; j <= n; ++j) {
			scanf("%d", &v);
			++K[(i + j) % 3][v];
		}
	}
	for (int i = 0; i < 3; ++i) {
		for (int j = 1; j <= c; ++j) {
			for (int s = 1; s <= c; ++s)
				T[i][j] += K[i][s] * D[s][j];
		}
	}
	x = LONG_MAX;
	for (int i = 1; i <= c; ++i) {
		for (int j = 1; j <= c; ++j) {
			if (i == j) continue;
			for (int k = 1; k <= c; ++k) {
				if (i == k || j == k)continue;
				v = T[0][i] + T[1][j] + T[2][k];
				if (x > v)
					x = v;
			}
		}
	}
	printf("%ld\n", x);
	return 0;
}