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() }

    val count = Array(3) { LongArray(c) }
    grid.mapIndexed { y, row -> row.forEachIndexed { x, i -> count[(y + x) % 3][i]++ } }

    fun colorToCost(i: Int, to: Int) = (0 until c)
        .map { count[i][it] * changeCosts[it][to] }.sum()

    var answer = Long.MAX_VALUE

    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 = colorToCost(0, c1) + colorToCost(1, c2) + colorToCost(2, c3)
                answer = Math.min(answer, sum)
            }
        }
    }

    println(answer)
}
