You are given a grid with N rows and N columns of squares, each initially painted with one of C colors. The grid is considered "good" if certain conditions are met. You need to repaint some squares to make the grid "good" and find the minimum sum of wrongness for all squares. Constraints: 1 ≤ N ≤ 500, 3 ≤ C ≤ 30, 1 ≤ D_{i,j} ≤ 1000 (i ≠ j), D_{i,j}=0 (i=j), 1 ≤ c_{i,j} ≤ C. Input format: N C D_{1,1} ... D_{1,C} ... D_{C,1} ... D_{C,C} c_{1,1} ... c_{1,N} ... c_{N,1} ... c_{N,N}. Output the minimum possible sum of wrongness. Example input: 2 3 0 1 1 1 0 1 1 4 0 1 2 3 3. Example output: 3.

# Buggy version:
from itertools import permutations

n, c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
cmat = [list(map(int, input().split())) for _ in range(n)]

dcnt = [[0] * c for _ in range(3)]
for i in range(n):
    for j in range(n):
        mod = (i + j) % 3
        dcnt[mod][c[i][j] - 1] += 1

ans = 10 ** 9
for color in permutations(range(c), 3):
    tmp = 0
    for tgt, cnt in zip(color, dcnt):
        tmp += sum(d[i][tgt] * cnt[i] for i in range(c))
    ans = min(ans, tmp)
print(ans)


# Fixed version:
from itertools import permutations

n, c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
cmat = [list(map(int, input().split())) for _ in range(n)]

dcnt = [[0] * c for _ in range(3)]
for i in range(n):
    for j in range(n):
        mod = (i + j) % 3
        dcnt[mod][cmat[i][j] - 1] += 1

ans = 10 ** 9
for color in permutations(range(c), 3):
    tmp = 0
    for tgt, cnt in zip(color, dcnt):
        tmp += sum(d[i][tgt] * cnt[i] for i in range(c))
    ans = min(ans, tmp)
print(ans)

# Buggy version:
def main():
    from sys import stdin
    def input():
        return stdin.readline().strip()
    
    n, c = map(int, input().split())
    d = [list(map(int, input().split())) for _ in range(c)]

    
    # if I can change the color of the same square many times
    # Warshall-Floyd algorithm
    for k in range(c):
        for i in range(c):
            for j in range(c):
                if d[i][j] > d[i] + d[j]:
                    d[i][j] = d[i][j]
    

    color = [list(map(int, input().split())) for _ in range(n)]

    counters = [[0] * c for _ in range(3)]
    for i in range(n):
        for j in range(n):
            counters[(i+j) % 3][color[i][j] - 1] += 1
    
    # full search
    cost = []
    for group in counters:
        l = []
        for i in range(c):
            num = 0
            for j in range(c):
                num += d[j][i] * group[j]
            l.append((num, i))
        l.sort()
        cost.append(l[c-3:])

    ans = 10 ** 9
    for i in range(3):
        for j in range(3):
            for k in range(3):
                if cost[0][i][1] != cost[1][j][1] and cost[1][j][1] != cost[2][k][1] and cost[2][k][1] != cost[0][i][1]:
                    if ans > cost[0][i][0] + cost[1][j][0] + cost[2][k][0]:
                        ans = cost[0][i][0] + cost[1][j][0] + cost[2][k][0]
    
    print(ans)

main()

# Fixed version:
def main():
    from sys import stdin
    def input():
        return stdin.readline().strip()
    
    n, c = map(int, input().split())
    d = [list(map(int, input().split())) for _ in range(c)]

    '''
    # if I can change the color of the same square many times
    # Warshall-Floyd algorithm
    for k in range(c):
        for i in range(c):
            for j in range(c):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]
    '''

    color = [list(map(int, input().split())) for _ in range(n)]

    counters = [[0] * c for _ in range(3)]
    for i in range(n):
        for j in range(n):
            counters[(i+j) % 3][color[i][j] - 1] += 1
    
    # full search
    cost = []
    for group in counters:
        l = []
        # from j to i
        for i in range(c):
            num = 0
            for j in range(c):
                num += d[j][i] * group[j]
            l.append((num, i))
        l.sort()
        cost.append(l[:3])

    ans = 10 ** 9
    for i in range(3):
        for j in range(3):
            for k in range(3):
                if cost[0][i][1] != cost[1][j][1] and cost[1][j][1] != cost[2][k][1] and cost[2][k][1] != cost[0][i][1]:
                    if ans > cost[0][i][0] + cost[1][j][0] + cost[2][k][0]:
                        ans = cost[0][i][0] + cost[1][j][0] + cost[2][k][0]
    
    print(ans)

main()

# Buggy version:
from  itertools import combinations
n,c=map(int,input().split())
d=[list(map(int,input().split())) for _ in range(c)]
c=[list(map(int,input().split())) for _ in range(n)]
a=[[0]*c for _ in range(3)]
for i in range(n):
	for j in range(n):
		a[(i+j)%3][c[i][j]-1]+=1
ans=10**9
for v in combinations(c,3):
	tmp=0
	for i in range(3):
		for j in range(30):
			tmp+=a[i][j]*c[j][v[i]]
	ans=min(ans,tmp)
print(ans)

# Fixed version:
from itertools import permutations
n,C=map(int,input().split())
d=[list(map(int,input().split())) for _ in range(C)]
c=[list(map(int,input().split())) for _ in range(n)]
a=[[0]*C for _ in range(3)]
for i in range(n):
	for j in range(n):
		a[(i+j)%3][c[i][j]-1]+=1
ans=10**9
for v in permutations(range(C),3):
	tmp=0
	for i in range(3):
		for j in range(C):
			tmp+=a[i][j]*d[j][v[i]]
	ans=min(ans,tmp)
print(ans)

# Buggy version:
N,C=map(int,input().split())
D=[list(map(int,input().split())) for i in range(C)]
A=[list(map(int,input().split())) for i in range(N)]
X=[[0]*C for i in range(3)]
for c in range(C):
  for i in range(N):
    for j in range(N):
      X[(i+j)%3][c]+=D[A[i][j]][c]
P=10**20
for i in range(C):
  for j in range(C):
    for k in range(C):
      if len(set([i,j,k]))==3:
        P=min(P,X[0][i]+X[1][j]+X[2][k])
print(P)

# Fixed version:
N,C=map(int,input().split())
D=[list(map(int,input().split())) for i in range(C)]
A=[list(map(int,input().split())) for i in range(N)]
X=[[0]*C for i in range(3)]
for c in range(C):
  for i in range(N):
    for j in range(N):
      X[(i+j)%3][c]+=D[A[i][j]-1][c]
P=10**20
for i in range(C):
  for j in range(C):
    for k in range(C):
      if len(set([i,j,k]))==3:
        P=min(P,X[0][i]+X[1][j]+X[2][k])
print(P)

# Buggy version:
N,C = list(map(int,input().split()))

discomforts = [[0]*(N+1)]
for _ in range(C):
    discomforts.append([0,*map(int,input().split())])
print(discomforts)
grid = [[0]*(N+1)]
for _ in range(N):
    grid.append([0,*map(int,input().split())])

color_counts = [[0]*(C+1) for i in range(3)]

for i in range(1,N+1):
    for j in range(1,N+1):
        color_counts[(i+j)%3][grid[i][j]] += 1

ans = float('inf')
for c0 in range(1,C+1):
    for c1 in range(1,C+1):
        for c2 in range(1,C+1):
            if c0 != c1 and c1 != c2 and c2 != c0:
                total = 0
                for i in range(1,C+1):
                    total += discomforts[i][c0]*color_counts[0][i]
                    total += discomforts[i][c1]*color_counts[1][i]
                    total += discomforts[i][c2]*color_counts[2][i]
                ans = min(ans,total)
print(ans)

# Fixed version:
N,C = list(map(int,input().split()))

discomforts = [[0]*(N+1)]
for _ in range(C):
    row = [0]
    row.extend(list(map(int,input().split())))
    discomforts.append(row)
grid = [[0]*(N+1)]
for _ in range(N):
    row = [0]
    row.extend(list(map(int,input().split())))
    grid.append(row)

color_counts = [[0]*(C+1) for i in range(3)]

for i in range(1,N+1):
    for j in range(1,N+1):
        color_counts[(i+j)%3][grid[i][j]] += 1

ans = float('inf')
for c0 in range(1,C+1):
    for c1 in range(1,C+1):
        for c2 in range(1,C+1):
            if c0 != c1 and c1 != c2 and c2 != c0:
                total = 0
                for i in range(1,C+1):
                    total += discomforts[i][c0]*color_counts[0][i]
                    total += discomforts[i][c1]*color_counts[1][i]
                    total += discomforts[i][c2]*color_counts[2][i]
                ans = min(ans,total)
print(ans)

# Buggy version:
from collections import defaultdict

N,C=map(int,input().split())
D=[list(map(int,input().split())) for _ in range(C)]
grid=[list(map(int,input().split())) for _ in range(N)]

mod_0=defaultdict(int)
mod_1=defaultdict(int)
mod_2=defaultdict(int)

for i in range(N):
    for j in range(N):
        n=(i+j+2)%3
        if n==0:
            mod_0[grid[i][j]]+=1
        elif n==1:
            mod_1[grid[i][j]]+=1
        else:
            mod_2[grid[i][j]]+=1

ans=float("inf")
for i in range(C):
    for j in range(C):
        if i==j:
            continue
        for k in range(C):
            if k in [i,j]:
                continue

            total
            for prev,cnt in mod_0.items():
                total+=D[prev-1][i]*cnt
            for prev,cnt in mod_1.items():
                total+=D[prev-1][j]*cnt
            for prev,cnt in mod_2.items():
                total+=D[prev-1][k]*cnt
            
            ans=min(ans,total)
print(ans)

# Fixed version:
from collections import defaultdict

N,C=map(int,input().split())
D=[list(map(int,input().split())) for _ in range(C)]
grid=[list(map(int,input().split())) for _ in range(N)]

mod_0=defaultdict(int)
mod_1=defaultdict(int)
mod_2=defaultdict(int)

for i in range(N):
    for j in range(N):
        n=(i+j+2)%3
        if n==0:
            mod_0[grid[i][j]]+=1
        elif n==1:
            mod_1[grid[i][j]]+=1
        else:
            mod_2[grid[i][j]]+=1

ans=float("inf")
for i in range(C):
    for j in range(C):
        if i==j:
            continue
        for k in range(C):
            if k in [i,j]:
                continue

            total=0
            for prev,cnt in mod_0.items():
                total+=D[prev-1][i]*cnt
            for prev,cnt in mod_1.items():
                total+=D[prev-1][j]*cnt
            for prev,cnt in mod_2.items():
                total+=D[prev-1][k]*cnt
            
            ans=min(ans,total)
print(ans)

# Buggy version:
import sys
input = sys.stdin.readline

n, c = [int(x) for x in input().split()]

d_list = [[int(x) for x in input().split()] for _ in range(c)]
c_ = [[int(x) for x in input().split()] for _ in range(n)]

mod_0 = [0] * c
mod_1 = [0] * c
mod_2 = [0] * c

for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            m = mod_0
        elif (i + j) % 3 == 1:
            m = mod_1
        else:
            m = mod_2
        for k in range(c):
            m[k] += d_list[c_[i][j] - 1][k]

ans = 10 ** 18
print(c)
for i in range(c):
    for j in range(i + 1, c):
        for k in range(j + 1, c):
            print(i, j, k)
            a = mod_0[i] + mod_1[j] + mod_2[k]
            b = mod_0[i] + mod_1[k] + mod_2[j]
            c__ = mod_0[j] + mod_1[i] + mod_2[k]
            d = mod_0[j] + mod_1[k] + mod_2[i]
            e = mod_0[k] + mod_1[i] + mod_2[j]
            f = mod_0[k] + mod_1[j] + mod_2[i]
            ans = min(ans, a, b, c__, d, e, f)

print(ans)

# Fixed version:
import sys
input = sys.stdin.readline

n, c = [int(x) for x in input().split()]

d_list = [[int(x) for x in input().split()] for _ in range(c)]
c_ = [[int(x) for x in input().split()] for _ in range(n)]

mod_0 = [0] * c
mod_1 = [0] * c
mod_2 = [0] * c

for i in range(n):
    for j in range(n):
        if (i + j) % 3 == 0:
            m = mod_0
        elif (i + j) % 3 == 1:
            m = mod_1
        else:
            m = mod_2
        for k in range(c):
            m[k] += d_list[c_[i][j] - 1][k]

ans = 10 ** 18

for i in range(c):
    for j in range(i + 1, c):
        for k in range(j + 1, c):
            a = mod_0[i] + mod_1[j] + mod_2[k]
            b = mod_0[i] + mod_1[k] + mod_2[j]
            c__ = mod_0[j] + mod_1[i] + mod_2[k]
            d = mod_0[j] + mod_1[k] + mod_2[i]
            e = mod_0[k] + mod_1[i] + mod_2[j]
            f = mod_0[k] + mod_1[j] + mod_2[i]
            ans = min(ans, a, b, c__, d, e, f)

print(ans)

# Buggy version:
from collections import Counter
from itertools import permutations

def main():
    N, C = map(int, input().split())
    D = [[int(x) for x in input().split()] for _ in range(C)]

    cnt = [Counter() for _ in range(3)]

    for i in range(N):
        c = [int(x)-1 for x in input().split()]
        for j in range(3):
            cnt[j].update(c[(3-(i+2)+j)%3::3])

    ans = 1000*500*500+5
    for p in permutations(range(C), 3):
        s = sum(D[k][p[j]] * v for k, v in cnt[j].items() for j in range(3))
        ans = min(ans, s)

    print(ans)

main()

# Fixed version:
from collections import Counter
from itertools import permutations

N, C = map(int, input().split())
D = [[int(x) for x in input().split()] for _ in range(C)]

cnt = [Counter() for _ in range(3)]

for i in range(N):
    c = [int(x)-1 for x in input().split()]
    for j in range(3):
        cnt[j].update(c[(3-(i+2)+j)%3::3])

ans = 1000*500*500+5
for p in permutations(range(C), 3):
    s = 0
    for j in range(3):
        for k, v in cnt[j].items():
            s += D[k][p[j]] * v
    ans = min(ans, s)

print(ans)

# Buggy version:
n,c=map(int,input().split())
d=[]
for i in range(c):
  d.append(list(map(int,input().split())))
col=[]
for i in range(n):
  col.append(list(map(int,input().split())))
lc1=[]
lc2=[]
lc3=[]
for i in range(c):
  ccount1=0
  ccount2=0
  ccount3=0
  for j in range(n):
    for k in range(n):
      if (j+k)%3==0:
        ccount1+=d[col[j][k]][i]
      elif (j+k)%3==1:
        ccount2+=d[col[j][k]][i]
      else:
        ccount3+=d[col[j][k]][i]
  lc1.append(ccount1)
  lc2.append(ccount2)
  lc3.append(ccount3)
min=10**10
for i in range(c):
  for j in range(c):
    for k in range(c):
      if i==j or j==k or i==k:
        pass
      else:
        if min>lc1[i]+lc2[j]+lc3[k]:
          min=lc1[i]+lc2[j]+lc3[k]
print(min)

# Fixed version:
n,c=map(int,input().split())
d=[]
for i in range(c):
  d.append(list(map(int,input().split())))
col=[]
for i in range(n):
  col.append(list(map(int,input().split())))
lc1=[]
lc2=[]
lc3=[]
for i in range(c):
  ccount1=0
  ccount2=0
  ccount3=0
  for j in range(n):
    for k in range(n):
      if (j+k)%3==0:
        ccount1+=d[col[j][k]-1][i]
      elif (j+k)%3==1:
        ccount2+=d[col[j][k]-1][i]
      else:
        ccount3+=d[col[j][k]-1][i]
  lc1.append(ccount1)
  lc2.append(ccount2)
  lc3.append(ccount3)
min=10**10
for i in range(c):
  for j in range(c):
    for k in range(c):
      if i==j or j==k or i==k:
        pass
      else:
        if min>lc1[i]+lc2[j]+lc3[k]:
          min=lc1[i]+lc2[j]+lc3[k]
print(min)

# Buggy version:
from collections import defaultdict
N, C = map(int, input().split())

D = [tuple(map(int, input().split())) for _ in range(C)]

d = [defaultdict(int) for i in range(3)]


for i in range(N):
    c = [int(x) for x in input().split()]
    for j in range(N):
        for k in range(C):
            d[(i+j) % 3][k] += D[c[j]-1][k]
print(d)

ans = 10**9
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i != j and j != k and k != i:
                ans = min(ans, d[0][i]+d[1][j]+d[2][k])

print(ans)


# Fixed version:
from collections import defaultdict
N, C = map(int, input().split())

D = [tuple(map(int, input().split())) for _ in range(C)]

d = [defaultdict(int) for i in range(3)]


for i in range(N):
    c = [int(x) for x in input().split()]
    for j in range(N):
        for k in range(C):
            d[(i+j) % 3][k] += D[c[j]-1][k]
# print(d)

ans = 10**9
for i in range(C):
    for j in range(C):
        for k in range(C):
            if i != j and j != k and k != i:
                ans = min(ans, d[0][i]+d[1][j]+d[2][k])

print(ans)

# Buggy version:
n,c = map(int,input().split())
D = [list(map(int,input().split())) for _ in range(c)]
C = [list(map(int,input().split())) for _ in range(n)]

color_count = [[0]*c for i in range(3)]
for i in range(n):
    for j in range(n):
        color_count[(i+j)%3][C[i][j]-1] += 1

print(color_count)

min_wrongness = 10**9

for i in range(c):
    for j in range(c):
        for k in range(c):
            if i!=j and j!=k and k!=i:
                wrongness = 0
                for l in range(3):
                    for m in range(c):
                        if l == 0:
                            wrongness += D[m][i]*color_count[l][m]
                        elif l == 1:
                            wrongness += D[m][j]*color_count[l][m]
                        else:
                            wrongness += D[m][k]*color_count[l][m]
                min_wrongness = min(min_wrongness,wrongness)
                
print(min_wrongness)

# Fixed version:
n,c = map(int,input().split())
D = [list(map(int,input().split())) for _ in range(c)]
C = [list(map(int,input().split())) for _ in range(n)]

color_count = [[0]*c for i in range(3)]
for i in range(n):
    for j in range(n):
        color_count[(i+j)%3][C[i][j]-1] += 1

min_wrongness = 10**9

for i in range(c):
    for j in range(c):
        for k in range(c):
            if i!=j and j!=k and k!=i:
                wrongness = 0
                for l in range(3):
                    for m in range(c):
                        if l == 0:
                            wrongness += D[m][i]*color_count[l][m]
                        elif l == 1:
                            wrongness += D[m][j]*color_count[l][m]
                        else:
                            wrongness += D[m][k]*color_count[l][m]
                min_wrongness = min(min_wrongness,wrongness)
                
print(min_wrongness)

# Buggy version:
import itertools
n,c=map(int,input().split())
ld=[list(map(int,input().split())) for i in range(c)]
lc=[list(map(int,input().split())) for i in range(n)]
ct=[[0 for i in range(c)] for i in range(3)]
for i in range(n):
  for j in range(n):
    ct[(i+j+2)%3][lc[i][j]-1]+=1
L=list(itertools.permutations([i for i in range(c)],3))
print(L)
ans=[]
for i in range(len(L)):
  ct2=0
  for j in range(3):
    for k in range(c):
      ct2+=ld[k][L[i][j]]*ct[j][k]
  ans.append(ct2)
print(min(ans))

# Fixed version:
import itertools
n,c=map(int,input().split())
ld=[list(map(int,input().split())) for i in range(c)]
lc=[list(map(int,input().split())) for i in range(n)]
ct=[[0 for i in range(c)] for i in range(3)]
for i in range(n):
  for j in range(n):
    ct[(i+j+2)%3][lc[i][j]-1]+=1
L=list(itertools.permutations([i for i in range(c)],3))
ans=[]
for i in range(len(L)):
  ct2=0
  for j in range(3):
    for k in range(c):
      ct2+=ld[k][L[i][j]]*ct[j][k]
  ans.append(ct2)
print(min(ans))

# Buggy version:
import itertools
N,C = map(int,input().split(' '))
D = [list(map(int,input().split(' '))) for i in [0]*C]
c = [list(map(int,input().split(' '))) for i in [0]*N]


l = [[],[],[]]
n = 0
for i in range(N):
	for j in range(i+1):
		l[n].append(c[i-j][j])
	n = (n+1) % 3
for i in range(N-1):
	for j in range(N-i-1):
		l[n].append(c[i+j+1][N-j-1])
	n = (n+1) % 3

d1,d2,d3 = [[sum([D[j-1][i] for j in l[n]]) for i in range(C)] for n in range(3)]

ans = 1000*500*500
colors = list(range(C))
for c1,c2,c3 in itertools.combinations(colors,3):
	ans = min(ans,d1[c1] + d2[c2] + d3[c3])
print(ans)







# Fixed version:
import itertools
N,C = map(int,input().split(' '))
D = [list(map(int,input().split(' '))) for i in [0]*C]
c = [list(map(int,input().split(' '))) for i in [0]*N]


l = [[],[],[]]
n = 0
for i in range(N):
	for j in range(i+1):
		l[n].append(c[i-j][j])
	n = (n+1) % 3
for i in range(N-1):
	for j in range(N-i-1):
		l[n].append(c[i+j+1][N-j-1])
	n = (n+1) % 3

d1,d2,d3 = [[sum([D[j-1][i] for j in l[n]]) for i in range(C)] for n in range(3)]

ans = 1000*500*500
colors = list(range(C))
for c1,c2,c3 in itertools.permutations(colors,3):
	ans = min(ans,d1[c1] + d2[c2] + d3[c3])
print(ans)

# Buggy version:
import sys
input = sys.stdin.readline

N, C = map(int, input().split())

grid_array = [[0] * C for _ in range(3)]

D_array = [list(map(int, input().split())) for _ in range(C)]

for i in range(N):
    C_array = map(int, input().split())
    for j, c in enumerate(C_array):
        grid_array[(i+j) % 3][c-1] += 1

print(D_array)

cost_array = [[0] * C for _ in range(3)]
for i in range(3):
    for j in range(C):
        cost = 0
        for k in range(C):
            cost += grid_array[i][k] * D_array[k][j]
        cost_array[i][j] = cost

ans = 10 ** 20

for i in range(C):
    for j in range(C):
        if j == i:
            continue
        for k in range(C):
            if k == i or k == j:
                continue
            ans = min(ans, cost_array[0][i] +
                      cost_array[1][j] + cost_array[2][k])
print(ans)


# Fixed version:
import sys
input = sys.stdin.readline

N, C = map(int, input().split())

grid_array = [[0] * C for _ in range(3)]

D_array = [list(map(int, input().split())) for _ in range(C)]

for i in range(N):
    C_array = map(int, input().split())
    for j, c in enumerate(C_array):
        grid_array[(i+j) % 3][c-1] += 1

# print(D_array)

cost_array = [[0] * C for _ in range(3)]
for i in range(3):
    for j in range(C):
        cost = 0
        for k in range(C):
            cost += grid_array[i][k] * D_array[k][j]
        cost_array[i][j] = cost

ans = 10 ** 20

for i in range(C):
    for j in range(C):
        if j == i:
            continue
        for k in range(C):
            if k == i or k == j:
                continue
            ans = min(ans, cost_array[0][i] +
                      cost_array[1][j] + cost_array[2][k])
print(ans)

# Buggy version:
N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c_map = [list(map(int, input().split())) for _ in range(N)]
count = [[0]*C for _ in range(3)]
for i in range(N):
    for j in range(N):
        c = c_map[i][j]
        amari = (i+j)%3
        count[amari][c-1]+=1
ans = float('inf')
for i in range(C):
    for j in range(C):
        for k in range(C):
            tmp = 0
            if i == k or j == k or i==j:
                continue
            else:
                for l in range(C):
                    tmp+=count[0][l]*D[l][i]
                    tmp+=count[1][l]*D[l][j]
                    tmp+=count[2][l]*D[l][k]
            ans = min(ans, tmp)
print(count)
print(ans)

# Fixed version:
N, C = map(int, input().split())
D = [list(map(int, input().split())) for _ in range(C)]
c_map = [list(map(int, input().split())) for _ in range(N)]
count = [[0]*C for _ in range(3)]
for i in range(N):
    for j in range(N):
        c = c_map[i][j]
        amari = (i+j)%3
        count[amari][c-1]+=1
ans = float('inf')
for i in range(C):
    for j in range(C):
        for k in range(C):
            tmp = 0
            if i == k or j == k or i==j:
                continue
            else:
                for l in range(C):
                    tmp+=count[0][l]*D[l][i]
                    tmp+=count[1][l]*D[l][j]
                    tmp+=count[2][l]*D[l][k]
            ans = min(ans, tmp)
print(ans)

# Buggy version:
from collections import defaultdict
tot = 10**12
n,c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(n)]
clr = [list(map(int, input().split())) for _ in range(n)]
l = [dict()]*3
for y in range(n):
  for x in range(n):
    l[(x+y)%3][clr[y][x]] += 1
for c1 in range(c):
  for c2 in range(c):
    if c1 == c2:
      continue
    for c3 in range(c):
      if c1==c3 or c2==c3:
        continue
      ctot = 0
      cl = [c1,c2,c3]
      for i in range(3):
        for x in l[i]:
          ctot += d[x-1][c[i]]*l[i][x]
      if tot > ctot:
        tot = ctot
print(tot)
      

# Fixed version:
from collections import defaultdict as ddict
tot = 10**12
n,c = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(c)]
clr = [list(map(int, input().split())) for _ in range(n)]
l = [ddict(int) for _ in range(3)]
for y in range(n):
  for x in range(n):
    l[(x+y)%3][clr[y][x]] += 1
for c1 in range(c):
  for c2 in range(c):
    if c1 == c2:
      continue
    for c3 in range(c):
      if c1==c3 or c2==c3:
        continue
      ctot = 0
      cl = [c1,c2,c3]
      for i in range(3):
        for x in l[i]:
          ctot += d[x-1][cl[i]]*l[i][x]
      if tot > ctot:
        tot = ctot
print(tot)

# Buggy version:
from itertools import*
n,c=map(int,input().split())
cost=[list(map(int,input().split()))for i in range(c)]
d=[[0]*c for i in range(3)]
for i in range(n):
    for j,v in enumerate(map(int,input().split())):
        d[(i+j)%3][v-1]+=1
print(min(sum(d[j][cmb[i]]*cost[i][j]for j in range(c)for i in range(3))for cmb in permutations(range(c),3)))

# Fixed version:
from itertools import*
n,c=map(int,input().split())
cost=[list(map(int,input().split()))for i in range(c)]
d=[[0]*c for i in range(3)]
for i in range(n):
    for j,v in enumerate(map(int,input().split())):
        d[(i+j)%3][v-1]+=1
print(min(sum(cost[j][cmb[i]]*d[i][j]for j in range(c)for i in range(3))for cmb in permutations(range(c),3)))

# Buggy version:
mport collections
N , C = map(int, input().split())
ds =[list(map(int, input().split())) for i in range(C)]
cs =[list(map(int, input().split())) for i in range(N)]
c0 = collections.defaultdict(int)
c1 = collections.defaultdict(int)
c2 = collections.defaultdict(int)
for i in range(N):
    for j in range(N):
        if (i+j) % 3 == 0:
            c0[cs[i][j]] += 1
        elif (i+j) % 3 == 1:
            c1[cs[i][j]] += 1
        else:
            c2[cs[i][j]] += 1
            
d = 10**9
for i in range(C):
    for j in range(C):
        if i == j:
            continue
        for k in range(C):
            if i == k or j == k:
                continue
            d0 = 0
            for l in c0:
                if l != i:
                    d0 += c0[l] * ds[l-1][i]
            for l in c1:
                if l != j:
                    d0 += c1[l] * ds[l-1][j]
            for l in c2:
                if l != k:
                    d0 += c2[l] * ds[l-1][k]
            if d > d0:
                d = d0
print(d)

# Fixed version:
import collections
N , C = map(int, input().split())
ds =[list(map(int, input().split())) for i in range(C)]
cs =[list(map(int, input().split())) for i in range(N)]
c0 = collections.defaultdict(int)
c1 = collections.defaultdict(int)
c2 = collections.defaultdict(int)
for i in range(N):
    for j in range(N):
        if (i+j) % 3 == 0:
            c0[cs[i][j]] += 1
        elif (i+j) % 3 == 1:
            c1[cs[i][j]] += 1
        else:
            c2[cs[i][j]] += 1
            
d = 10**9
for i in range(C):
    for j in range(C):
        if i == j:
            continue
        for k in range(C):
            if i == k or j == k:
                continue
            d0 = 0
            for l in c0:
                d0 += c0[l] * ds[l-1][i]
            for l in c1:
                d0 += c1[l] * ds[l-1][j]
            for l in c2:
                d0 += c2[l] * ds[l-1][k]
            if d > d0:
                d = d0
            
print(d)

# Buggy version:
N,C = map(int, input().split())
cost = [list(map(int, input().split())) for _ in range(C)]
color = [list(map(int, input().split())) for _ in range(N)]

mod3 = {0:[], 1:[], 2:[]}
for i in range(N):
    for j in range(N):
        m = (i+j)%3
        mod3[m].append(color[i][j])
        
from collections import Counter
from itertools import combinations, permutations
cnts = [Counter(mod3[i]) for i in range(3)]
# print(cnts)
ans = float('inf')
for comb in combinations(range(C), 3):
    for p in permutations(comb):
        cond = 0
        for i in range(3):
            for col in cnts[i].keys():
                cond += cnts[i][col]*cost[col][p[i]]
        ans = min(ans, cond)
        #print(cond, p)
print(ans)
    

# Fixed version:
N,C = map(int, input().split())
cost = [list(map(int, input().split())) for _ in range(C)]
color = [list(map(lambda x:int(x)-1, input().split())) for _ in range(N)]

mod3 = {0:[], 1:[], 2:[]}
for i in range(N):
    for j in range(N):
        m = (i+j)%3
        mod3[m].append(color[i][j])
        
from collections import Counter
from itertools import combinations, permutations
cnts = [Counter(mod3[i]) for i in range(3)]
# print(cnts)
ans = float('inf')
for comb in combinations(range(C), 3):
    for p in permutations(comb):
        cond = 0
        for i in range(3):
            for col in cnts[i].keys():
                cond += cnts[i][col]*cost[col][p[i]]
        ans = min(ans, cond)
        #print(cond, p)
print(ans)

# Buggy version:
from itertools import permutations
from collections import deque
from collections import Counter
N, C = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]

r0 = deque()
r1 = deque()
r2 = deque()
for i in range(N):
    for j in range(N):
        rest = (i+1+j+1) % 3
        if rest == 0:
            r0.append(c[i][j]-1)
        elif rest == 1:
            r1.append(c[i][j]-1)
        else:
            r2.append(c[i][j]-1)
c0 = Counter(r0)
c1 = Counter(r1)
c2 = Counter(r2)
ans = 10**10
for p in permutations([i for i in range(C)], 3):
    point = 0
    point += sum([d[k][p[0] * v] for k, v in c0.items()])
    point += sum([d[k][p[1] * v] for k, v in c1.items()])
    point += sum([d[k][p[2] * v] for k, v in c2.items()])
    ans = min(ans, point)
print(ans)


# Fixed version:
from itertools import permutations
from collections import deque
from collections import Counter
N, C = map(int, input().split())
d = [list(map(int, input().split())) for _ in range(C)]
c = [list(map(int, input().split())) for _ in range(N)]

r0 = deque()
r1 = deque()
r2 = deque()
for i in range(N):
    for j in range(N):
        rest = (i+1+j+1) % 3
        if rest == 0:
            r0.append(c[i][j]-1)
        elif rest == 1:
            r1.append(c[i][j]-1)
        else:
            r2.append(c[i][j]-1)
c0 = Counter(r0)
c1 = Counter(r1)
c2 = Counter(r2)
ans = 10**10
for p in permutations([i for i in range(C)], 3):
    point = 0
    point += sum([d[k][p[0]]* v for k, v in c0.items()])
    point += sum([d[k][p[1]]* v for k, v in c1.items()])
    point += sum([d[k][p[2]]* v for k, v in c2.items()])
    ans = min(ans, point)
print(ans)

# Buggy version:
N, C = map(int, input().split())
D = []
for i in range(C):
    D.append(list(map(int, input().split())))

c_arr = []
for i in range(N):
    c_arr.append(list(map(int, input().split())))


c_arr1 = []
c_arr2 = []
c_arr3 = []

for i in range(N):
    for j in range(N):
        if (i+j)%3 == 0: 
            c_arr1.append(c_arr[i][j])
        if (i+j)%3 == 1: 
            c_arr2.append(c_arr[i][j])
        if (i+j)%3 == 2: 
            c_arr3.append(c_arr[i][j])

tmp = 1000*500*500

def cost(arr, aft):
    sum = 0
    for i in range(len(arr)):
        sum += D[arr[i]-1][aft]
    return sum

ans_arr = []

for l in range(C):
    for m in range(C):
        if l == m:
            pass
        else:
            for n in range(C):
                if l == n or m == n:
                    pass
                else:
                    print(l,m,n)
                    ans_arr.append(cost(c_arr1, l) + cost(c_arr2, m) + cost(c_arr3, n))

print(min(ans_arr))

# Fixed version:
N, C = map(int, input().split())
D = []
for i in range(C):
    D.append(list(map(int, input().split())))

c_arr = []
for i in range(N):
    c_arr.append(list(map(int, input().split())))


c_arr1 = []
c_arr2 = []
c_arr3 = []

for i in range(N):
    for j in range(N):
        if (i+j)%3 == 0: 
            c_arr1.append(c_arr[i][j])
        if (i+j)%3 == 1: 
            c_arr2.append(c_arr[i][j])
        if (i+j)%3 == 2: 
            c_arr3.append(c_arr[i][j])

tmp = 1000*500*500

def cost(arr, aft):
    sum = 0
    for i in range(len(arr)):
        sum += D[arr[i]-1][aft]
    return sum

ans_arr1 = []
ans_arr2 = []
ans_arr3 = []

for l in range(C):
    ans_arr1.append(cost(c_arr1, l))
for l in range(C):
    ans_arr2.append(cost(c_arr2, l))
for l in range(C):
    ans_arr3.append(cost(c_arr3, l))


ans_arr = []
for l in range(C):
    for m in range(C):
        for n in range(C):
            if l == n or n == m or m == l:
                pass
            else:
                ans_arr.append(ans_arr1[l]+ans_arr2[m]+ans_arr3[n])

print(min(ans_arr))

# Buggy version:
import itertools
N,C = map(int,input().split())
D = [list(map(int,input().split())) for i in range(C)]
grid = [list(map(int,input().split())) for i in range(N)]
color = list(range(1,C+1))
ans = float('inf')
for x,y,z in itertools.permutations(color,3):
    print(x,y,z)
    res = 0
    for i in range(1,N+1):
        for j in range(1,N+1):
            if (i+j) % 3 == 0:
                res += D[grid[i-1][j-1]-1][x-1]
            elif (i+j) % 3 == 1:
                res += D[grid[i-1][j-1]-1][y-1]
            elif (i+j) % 3 == 2:
                res += D[grid[i-1][j-1]-1][z-1]
    if res < ans:
        ans = res
print(ans)

# Fixed version:
import itertools
N,C = map(int,input().split())
D = [list(map(int,input().split())) for i in range(C)]
grid = [list(map(int,input().split())) for i in range(N)]
l1 = [0]*C
l2 = [0]*C
l3 = [0]*C
for i in range(1,N+1):
    for j in range(1,N+1):
        if (i+j) % 3 == 0:
            l1[grid[i-1][j-1]-1] += 1
        elif (i+j) % 3 == 1:
            l2[grid[i-1][j-1]-1] += 1
        elif (i+j) % 3 == 2:
            l3[grid[i-1][j-1]-1] += 1
color = list(range(1,C+1))
ans = float('inf')
for x,y,z in itertools.permutations(color,3):
    res = 0
    for i in range(C):
        res += D[i][x-1]*l1[i]
    for i in range(C):
        res += D[i][y-1]*l2[i]
    for i in range(C):
        res += D[i][z-1]*l3[i]
    if res < ans:
        ans = res
print(ans)

# Buggy version:
N,C=map(int,input().split())
D=[list(map(int,input().split())) for _ in range(C)]
G=[list(map(int,input().split())) for _ in range(N)]
C0=[0]*(C+1)
C1=[0]*(C+1)
C2=[0]*(C+1)

for x in range(N):
    for y in range(N):
        if (x+y+2)%3==0: C0[G[x][y]]+=1
        elif (x+y+2)%3==1: C1[G[x][y]]+=1
        elif (x+y+2)%3==2: C2[G[x][y]]+=1

miniwa=250000000
for c0 in range(1,C+1):
    for c1 in range(1,C+1):
        for c2 in range(1,C+1):
            if (c1-c0)*(c2-c1)*(c0-c2)==0: break
            iwa=0
            for i in range(1,C+1):
                iwa+=(D[i-1][c0-1]*C0[i]+D[i-1][c1-1]*C1[i]+D[i-1][c2-1]*C2[i])
            miniwa=min(miniwa,iwa)
print(miniwa)

# Fixed version:
N,C=map(int,input().split())
D=[list(map(int,input().split())) for _ in range(C)]
G=[list(map(int,input().split())) for _ in range(N)]
C0=[0]*(C+1)
C1=[0]*(C+1)
C2=[0]*(C+1)

for x in range(N):
    for y in range(N):
        if (x+y+2)%3==0: C0[G[x][y]]+=1
        elif (x+y+2)%3==1: C1[G[x][y]]+=1
        elif (x+y+2)%3==2: C2[G[x][y]]+=1

miniwa=250000000
for c0 in range(1,C+1):
    for c1 in range(1,C+1):
        for c2 in range(1,C+1):
            if (c1-c0)*(c2-c1)*(c0-c2)==0: continue
            iwa=0
            for i in range(1,C+1):
                iwa+=(D[i-1][c0-1]*C0[i]+D[i-1][c1-1]*C1[i]+D[i-1][c2-1]*C2[i])
            miniwa=min(miniwa,iwa)
print(miniwa)

# Buggy version:
import itertools
import sys
input = sys.input.readline()


def main():
    N, C = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(C)]
    CC = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]

    cost = [[0 for _ in range(C)] for _ in range(3)]
    for c in range(C):
        for i in range(N):
            for j in range(N):
                cost[(i + j) % 3][c] += D[CC[i][j]][c]

    res = float("inf")
    color = [i for i in range(C)]
    for i, c in enumerate(list(itertools.permutations(color, 3))):
        tmp = 0
        for it in range(3):
            tmp += cost[it][c[it]]
        res = min(res, tmp)

    print(res)

main()


# Fixed version:
import itertools


def main():
    N, C = map(int, input().split())
    D = [list(map(int, input().split())) for _ in range(C)]
    CC = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]

    cost = [[0 for _ in range(C)] for _ in range(3)]
    for c in range(C):
        for i in range(N):
            for j in range(N):
                cost[(i + j) % 3][c] += D[CC[i][j]][c]

    res = float("inf")
    color = [i for i in range(C)]
    for i, c in enumerate(list(itertools.permutations(color, 3))):
        tmp = 0
        for it in range(3):
            tmp += cost[it][c[it]]
        res = min(res, tmp)

    print(res)

main()

# Buggy version:
n,c=map(int,input().split())
d=[list(map(int,input().split()))for _ in range(c)]
l=[[i for i in[0]*c]for _ in range(3)]
for i in range(n):
  t=list(map(int,input().split()))
  for j in range(n):
    l[(i+j)%3][t[j]-1]+=1
c=10**18
for i in range(c):
  for j in range(c):
    for k in range(c):
      if i==j or j==k or k==i:continue
      c=min(c,sum(d[x][i]*l[0][x]+d[x][j]*l[1][x]+d[x][k]*l[2][x]for x in range(c)))
print(c)

# Fixed version:
n,c=map(int,input().split())
d=[list(map(int,input().split()))for _ in range(c)]
l=[[i for i in[0]*c]for _ in range(3)]
for i in range(n):
  t=list(map(int,input().split()))
  for j in range(n):
    l[(i+j)%3][t[j]-1]+=1
a=10**18
for i in range(c):
  for j in range(c):
    for k in range(c):
      if i==j or j==k or k==i:continue
      a=min(a,sum(d[x][i]*l[0][x]+d[x][j]*l[1][x]+d[x][k]*l[2][x]for x in range(c)))
print(a)

# Buggy version:
n,c=map(int,input().split())
D=[]
for i in range(c):
    D.append(list(map(int,input().split())))
C=[]
for i in range(n):
    C.append(list(map(int,input().split())))

print(D)

C1=[]
C2=[]
C3=[]
for i in range(n):
    for j in range(n):
        f=(i+j)%3
        if f==0:
            C1.append(C[i][j])
        if f==1:
            C2.append(C[i][j])
        if f==2:
            C3.append(C[i][j])
        

miniwa=1000*500*500

print(C3)

for c1 in range(0,c):
    iwa1=sum(D[i-1][c1] for i in C1)
    for c2 in range(0,c):
        iwa2=sum(D[j-1][c2] for j in C2)
        for c3 in range(0,c):
            if c1!=c2 and c2!=c3 and c3!=c1 :
                iwa3=sum(D[k-1][c3] for k in C3)
                iwa=iwa1+iwa2+iwa3
                miniwa=min(miniwa,iwa)

print(miniwa)


# Fixed version:
n,c=map(int,input().split())
D=[]
for i in range(c):
    D.append(list(map(int,input().split())))
C=[]
for i in range(n):
    C.append(list(map(int,input().split())))

#print(D)

C1=[]
C2=[]
C3=[]
for i in range(n):
    for j in range(n):
        f=(i+j)%3
        if f==0:
            C1.append(C[i][j])
        if f==1:
            C2.append(C[i][j])
        if f==2:
            C3.append(C[i][j])
        

miniwa=1000*500*500

#print(C3)
iwa1=[]
iwa2=[]
iwa3=[]

for cc in range(0,c):
    iwa1.append(sum(D[i-1][cc] for i in C1))
    iwa2.append(sum(D[i-1][cc] for i in C2))
    iwa3.append(sum(D[i-1][cc] for i in C3))

for c1 in range(0,c):
    for c2 in range(0,c):
        for c3 in range(0,c):
            if c1!=c2 and c2!=c3 and c3!=c1 :
                iwa=iwa1[c1]+iwa2[c2]+iwa3[c3]
                miniwa=min(miniwa,iwa)

print(miniwa)

# Buggy version:
from itertools import product
from collections import Counter
 
n, c = map(int, input().split())
color_costs = [list(map(int, input().split())) for _ in range(c)]
matrix = [list(map(int, input().split())) for _ in range(n)]

colord = {(i, j):cost for i, row in enumerate(color_costs)
                      for j, cost in enumerate(row)}
 
res = []
for n in range(3):
  color_count = Counter(c-1 for i, row in enumerate(matrix) 
                            for j, c in enumerate(row) 
                            if (i + j) % 3 == n)
  def color_cost(color):
    return sum(colord[ccolor, color] * ccount for ccolor, ccount in color_count.items())
  cx = [(color, color_cost(color)) for color in range(c)]
  sorted_by_cost = sorted(cx, key=lambda x:x[1])
  cheapest3 = sorted_by_cost[:3]
  res.append(cheapest3)

color_pickss = product(*res)
filtered_unique = (picks for picks in color_pickss if len(set(x[0] for x in picks)) == 3)
costs = (sum(x[1] for x in picks) for pick in filtered_unique)
print(min(costs))

# Fixed version:
from itertools import product
from collections import Counter
 
n, c = map(int, input().split())
color_costs = [list(map(int, input().split())) for _ in range(c)]
matrix = [list(map(int, input().split())) for _ in range(n)]

colord = {(i, j):cost for i, row in enumerate(color_costs)
                      for j, cost in enumerate(row)}
 
res = []
for n in range(3):
  color_count = Counter(c-1 for i, row in enumerate(matrix) 
                            for j, c in enumerate(row) 
                            if (i + j) % 3 == n)
  def color_cost(color):
    return sum(colord[ccolor, color] * ccount for ccolor, ccount in color_count.items())
  cx = [(color, color_cost(color)) for color in range(c)]
  sorted_by_cost = sorted(cx, key=lambda x:x[1])
  cheapest3 = sorted_by_cost[:3]
  res.append(cheapest3)

color_pickss = product(*res)
filtered_unique = (picks for picks in color_pickss if len(set(x[0] for x in picks)) == 3)
costs = (sum(x[1] for x in picks) for picks in filtered_unique)
print(min(costs))

# Buggy version:
N,C = [int(i) for i in input().split()]
D = [[int(j) for j in input().split()] for i in range(C)]
c_temp = [[int(j)-1 for j in input().split()] for i in range(N)]
c = [[0 for i in range(C)] for j in range(3)]
print(c)
for i in range(N):
    for j in range(N):
        c[(i+j+2)%3][c_temp[i][j]] += 1
        print((i+j+2)%3, c_temp[i][j])

min = 100000
for i in [ii for ii in range(C)]:
    for j in [jj for jj in range(C) if jj != i]:
        for k in [kk for kk in range(C) if kk != i and kk != j]:
            count = sum([D[x][i]*c[0][x] + D[x][j]*c[1][x] + D[x][k]*c[2][x] for x in range(C)])
            if min > count:
                min = count
print(min)




# Fixed version:
N,C = [int(i) for i in input().split()]
D = [[int(j) for j in input().split()] for i in range(C)]
c_temp = [[int(j)-1 for j in input().split()] for i in range(N)]
c = [[0 for i in range(C)] for j in range(3)]
for i in range(N):
    for j in range(N):
        c[(i+j)%3][c_temp[i][j]] += 1

min = 10**15
for i in [ii for ii in range(C)]:
    for j in [jj for jj in range(C) if jj != i]:
        for k in [kk for kk in range(C) if kk != i and kk != j]:
            count = sum([D[x][i]*c[0][x] + D[x][j]*c[1][x] + D[x][k]*c[2][x] for x in range(C)])
            if min > count:
                min = count
print(min)

# Buggy version:
# 基本は３で割ったあまり毎に変換コストを計算する.
# a[i][j] i種類目がj色に変わる時のコストと計算し、それの合計のminを取る

import numpy as np
N,C = map(int,input().split())
a = np.zeros((3,C))
D = np.array([ list(map(int,input().split()))) for i in range(C)])
c = np.array([ list(map(int,input().split()))) for i in range(N)])


for i in range(N):
    for j in range(N):
        a[(i+j)%3] += D[c[i][j]-1]

sum_arr = []
for C1 in range(C):
    for C2 in range(C):
        for C3 in range(C):
            if C1 != C2 and C2 != C3 and C3 != C1:
                sum_arr.append(a[0][C1]+a[1][C2]+a[2][C3])

print(int(min(l)))


# Fixed version:
# 基本は３で割ったあまり毎に変換コストを計算する.
# a[i][j] i種類目がj色に変わる時のコストと計算し、それの合計のminを取る

import numpy as np
N,C = map(int,input().split())
a = np.zeros((3,C))
D = np.array([ list(map(int,input().split())) for i in range(C)])
c = np.array([ list(map(int,input().split())) for i in range(N)])


for i in range(N):
    for j in range(N):
        a[(i+j)%3] += D[c[i][j]-1]

sum_arr = []
for C1 in range(C):
    for C2 in range(C):
        for C3 in range(C):
            if C1 != C2 and C2 != C3 and C3 != C1:
                sum_arr.append(a[0][C1]+a[1][C2]+a[2][C3])

print(int(min(sum_arr)))