fun main(args: Array<String>) = yorukatsu17e()

fun yorukatsu17e() {
    val (n, c) = readLine()!!.split(' ').map { it.toInt() }
    val changeCosts = (1..c).map { readLine()!!.split(' ').map { it.toLong() } }
    val grid = Array(n) { readLine()!!.split(' ').map { it.toInt() - 1 }.toIntArray() }

    data class YXValue(val group: Int, val value: Int)

    val groupingBy = grid.mapIndexed { y, row ->
        row.mapIndexed { x, i -> YXValue((y + x) % 3, i) }
    }.flatten().groupBy { it.group }.mapValues { it.value.map { it.value } }
    val one = groupingBy[0].orEmpty()
    val two = groupingBy[1].orEmpty()
    val three = groupingBy[2].orEmpty()
    var answer = Long.MAX_VALUE

    val costOne = LongArray(c + 1)
    val costTwo = LongArray(c + 1)
    val costThree = LongArray(c + 1)
    for (i in 0 until c) {
        costOne[i] = one.map { changeCosts[it][i] }.sum()
        costTwo[i] = two.map { changeCosts[it][i] }.sum()
        costThree[i] = three.map { changeCosts[it][i] }.sum()
    }

    for (c1 in 0 until c) {
        for (c2 in 0 until c) {
            if (c2 == c1) continue
            for (c3 in 0 until c) {
                if (c3 == c1 || c3 == c2) continue
                val sum = costOne[c1] + costTwo[c2] + costThree[c3]
                answer = Math.min(answer, sum)
            }
        }
    }

    println(answer)
}
