object Main extends App {
  val scan = new java.util.Scanner(System.in)
  val n, c = scan.next.toInt
  val ds = Array.fill(c,c)(0)
  val cs = Array.fill(n,n)(0)
  for(i <- 0 until c; l <- 0 until c) ds(i)(l) = scan.next().toInt
  for(i <- 0 until n; l <- 0 until n) cs(i)(l) = scan.next().toInt - 1

  val c0 = Array.fill(c)(0)
  for(i <- 1 to n; l <- 1 to n; if (i+l) % 3 == 0) c0(cs(i-1)(l-1)) += 1
  val c1 = Array.fill(c)(0)
  for(i <- 1 to n; l <- 1 to n; if (i+l) % 3 == 1) c1(cs(i-1)(l-1)) += 1
  val c2 = Array.fill(c)(0)
  for(i <- 1 to n; l <- 1 to n; if (i+l) % 3 == 2) c2(cs(i-1)(l-1)) += 1

  val ns = for (
    i <- 0 until c;
    j <- 0 until c; if i != j; 
    k <- 0 until c; if i != k && j != k
  ) yield (c0.zip(0 to c).map(t => t._1 * ds(t._2)(i)).sum
          + c1.zip(0 to c).map(t => t._1 * ds(t._2)(j)).sum
          + c2.zip(0 to c).map(t => t._1 * ds(t._2)(k)).sum)

  println(ns.min)
}