fun main(args:Array<String>):Unit{
    val (n, c) = readLine()!!.split(' ').map(String::toInt)
    val differ = Array(c){
        readLine()!!.split(' ').map(String::toInt).toTypedArray()
    }
    val currentColor = Array(n){
        readLine()!!.split(' ').map{it.toInt() - 1}.toTypedArray()
    }
    val colors = (0 until 3).map{mod ->
        val array = Array(c){0}
        for (x in 0 until n){
            for (y in (3 * n - x + mod) % 3 until n step 3){
                array[currentColor[x][y]]++
            }
        }
        array
    }.toTypedArray()
    var min = Int.MAX_VALUE
    for (i in 0 until c){
        for (j in 0 until c){
            if (i != j){
                for (k in 0 until c){
                    if (i != k && j != k){
                        var sum = 0
                        for (color in 0 until c){
                            sum += colors[0][color] * differ[color][i] + colors[1][color] * differ[color][j] + colors[2][color] * differ[color][k]
                        }
                        if (min > sum)
                            min = sum
                    }
                }
            }
        }
    }
    println(min)
}