#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
typedef long long  ll;
#define rep(i,s,n)for(ll i=s;i<n;i++)
#define repe(i,s,n)for(ll i=s;i<=n;i++)

static const ll MOD = 1e9 + 7;

ll N, C;
ll d[31][31] = {};
ll c[501][501] = {};
ll e[30][3] = {};
int main()
{
	cin >> N >> C;
	repe(i, 1, C)repe(j, 1, C)cin >> d[i][j];
	repe(i, 1, N)repe(j, 1, N)cin >> c[i][j];

	repe(k, 1, C) {
		repe(i, 1, N)repe(j, 1, N) {
			e[k][(i + j) % 3] += d[c[i][j]][k];
		}
	}

	ll ans = 1 << 30;
	repe(i, 1, C) {
		repe(j, 1, C) {
			if (i != j) {
				repe(k, 1, C) {
					if (i != k && j != k) {
						ans = min(ans, e[i][0] + e[j][1] + e[k][2]);
					}
				}
			}
		}
	}

	cout << ans << endl;

	return 0;
}