fun main(args: Array<String>) {
    val (N, C) = listOfInt()
    val D = Array(C) { listOfInt().toIntArray() }
    val t = Array(3) { IntArray(C) }
    repeat(N) { i ->
        listOfInt().forEachIndexed { j, x ->
            t[(i + j) % 3][x - 1] += 1
        }
    }
    var ans = Int.MAX_VALUE
    for (i in 0 until C) {
        for (j in 0 until C) {
            if (i == j) continue
            for (k in 0 until C) {
                if (i == k || j == k) continue
                var x = 0
                x += (0 until C).map { D[it][i] * t[0][it] }.sum()
                x += (0 until C).map { D[it][j] * t[1][it] }.sum()
                x += (0 until C).map { D[it][k] * t[2][it] }.sum()
                ans = Math.min(x, ans)
            }
        }
    }
    println(ans)
}
fun next() = readLine()!!
fun nextInt() = next().toInt()
fun listOfString() = next().split(" ")
fun listOfInt() = listOfString().map { it.toInt() }