import scala.io.{StdIn => in}
import scala.collection.{mutable => mu}

object Main extends App {
  val Array(n, c) = in.readLine.split(" ").map(_.toInt)
  val dcf = Iterator.continually(in.readLine)
    .take(c).map(_.split(" ").map(_.toInt)).toArray
  val pallet = Iterator.continually(in.readLine)
    .take(n).map(_.split(" ").map(_.toInt)).toArray

  val group = Array.fill(3)(mu.ArrayBuffer.empty[Int])
  for {
    i <- 0 until n
    j <- 0 until n
  } {
    val rem = (i + j) % 3
    group(rem) += pallet(i)(j)
  }
  // group.foreach(s => debug(s.mkString(" ")))
  val table = for(g <- group.indices) yield {
    for(i <- 0 until c) yield {
      group(g)./:(0)((acc, j) => acc + dcf(j-1)(i))
    }
  }

  // debug(table.mkString(" "))

  def dfsEnum(d:Int, n:Int):Int = {
    // d進 n個列挙
    val enum = Array.ofDim[Int](n)
    var ret = Int.MaxValue
  
    def evalute():Unit = {
      if(enum.toSet.size == 3) {
        val res = 
          enum.indices.map(i => table(i)(enum(i))).sum
        ret = math.min(ret, res)
        // debug(enum.mkString(" "), " ", res)
      }
    }
  
    def dfs(cnt:Int):Unit = {
      if(cnt == n) evalute
      else {
        for(i <- 0 until c) {
          enum(cnt) = i
          dfs(cnt+1)
        }
      }
    }
  
    dfs(0)
    ret
  }

  val ans = dfsEnum(c,3)
  println(ans)

  def debug(any:Any*):Unit = {
    if(this.getClass.toString != "class Main$")
      println(any.mkString(" "))
  }
}