#include <iostream>


int n, c; int d[30][39]; int t[3][30];
int main() {
	std::cin >> n >> c;
	for (int i = 0; i < c; ++i)for (int j = 0; j < c; ++j)
		std::cin >> d[i][j];
	for (int i = 0; i < n; ++i)
		for (int j = 0; j < n; ++j) {
			int x;
			std::cin >> x;
			++t[(i + j) % 3][x - 1];
		}
	int res = 1 << 30;
	for (int i = 0; i < c; ++i)for (int j = 0; j < c; ++j)
		if (i != j)
			for (int k = 0; k < c; ++k)
				if (i != k && j != k) {
					int tt = 0;
					for (int l = 0; l < c; ++l)tt += d[l][i] * t[0][l];
					for (int l = 0; l < c; ++l)tt += d[l][j] * t[1][l];
					for (int l = 0; l < c; ++l)tt += d[l][k] * t[2][l];
					if (tt < res)
						res = tt;
				}
	std::cout << res << std::endl;
	return 0;
}
