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 = for(i <- 1 to n; l <- 1 to n; if (i+l) % 3 == 0) yield cs(i-1)(l-1)
  val c1 = for(i <- 1 to n; l <- 1 to n; if (i+l) % 3 == 1) yield cs(i-1)(l-1)
  val c2 = for(i <- 1 to n; l <- 1 to n; if (i+l) % 3 == 2) yield cs(i-1)(l-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.map(ds(_)(i)).sum + c1.map(ds(_)(j)).sum + c2.map(ds(_)(k)).sum

  println(ns.min)
}