import std.stdio, std.conv, std.string;
import std.algorithm, std.array, std.container;
import std.numeric, std.math;
import core.bitop;

T RD(T = string)() { static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }

long mod = pow(10, 9) + 7;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

void main()
{
	auto N = RD!long;
	auto C = RD!long;
	long[][] D;
	foreach (i; 0..C)
	{
		D ~= RDR.split.to!(long[]);
	}
	long[][] c;
	foreach (i; 0..N)
	{
		c ~= RDR.split.to!(long[]);
	}

	auto cnt = new long[][](3, C);
	foreach (i; 0..N)
	{
		foreach (j; 0..N)
		{
			foreach (k; 0..C)
			{
				cnt[(i+j+2)%3][k] += D[c[i][j]-1][k];
			}
		}
	}

	long[][] pat = [
		[0, 1, 2],
		[0, 2, 1],
		[1, 0, 2],
		[1, 2, 0],
		[2, 0, 1],
		[2, 1, 0]];
	long ans = long.max;
	foreach (arr; pat)
	{
		long[] used;
		long tmpAns;
		foreach (i; arr)
		{
			long best = long.max;
			long bestPos;
			foreach (j; 0..C)
			{
				if (used.countUntil(j) != -1) continue;
				if (cnt[i][j] < best)
				{
					best = cnt[i][j];
					bestPos = j;
				}
			}
			tmpAns += best;
			used   ~= bestPos;
		}
		ans = min(ans, tmpAns);
	}

	writeln(ans);
	stdout.flush();
}