#include<stdio.h>
int main(void){
  char *s="python3 -c\""
"n,c=map(int,input().split())\n"
"d=[list(map(int,input().split()))for _ in range(c)]\n"
"l=[[i for i in[0]*c]for _ in range(3)]\n"
"for i in range(n):\n"
"  t=list(map(int,input().split()))\n"
"  for j in range(n):\n"
"    l[(i+j)%3][t[j]-1]+=1\n"
"a=10**18\n"
"for i in range(c):\n"
"  for j in range(c):\n"
"    for k in range(c):\n"
"      if i==j or j==k or k==i:continue\n"
"      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)))\n"
"print(a)\n"
"\"";
  system(s);
  return 0;
}            