fun main(args: Array<String>) {
    val (N, C) = readLine()!!.split(" ").map{it.toInt()}

    val D = Array(C) { readLine()!!.split(" ").map{it.toLong()} }
    val c = Array(N) { readLine()!!.split(" ").map{it.toInt()} }

    val a = Array(3) { LongArray(C) { 0L } }

    for (i in c.indices) for (j in c[i].indices) {
        val k = (i + j + 2) % 3

        a[k][c[i][j] - 1] += 1L
    }

    var res = 1e18.toLong()
    for (c1 in 0 until C) for (c2 in D.indices) for (c3 in D.indices) {
        if (c1 == c2 || c2 == c3 || c3 == c1) continue

        var s = 0L
        val cs = arrayOf(c1, c2, c3)
        for (i in a.indices) {
            for (j in a[i].indices) {
                s += a[i][j] * D[j][cs[i]]
            }
        }

        res = Math.min(res, s)
    }

    println(res)
}
