fun main(args: Array<String>) {
    val (N, C) = readLine()!!.split(" ").map { it.toInt() }
    val D = mutableListOf<IntArray>()
    val c = mutableListOf<IntArray>()
    (1..C).forEach {
        val d = readLine()!!.split(" ").map { it.toInt() }
        D.add(d.toIntArray())
    }
    (1..N).forEach {
        val ci = readLine()!!.split(" ").map { it.toInt() }
        c.add(ci.toIntArray())
    }




    val zeroMod3Scores = IntArray(C)
    val oneMod3Scores = IntArray(C)
    val twoMod3Scores = IntArray(C)

    // O(CN^2)
    (1..C).forEach { to ->
        var costZero = 0
        var costOne = 0
        var costTwo = 0
        (0 until N).forEach { x ->
            (0 until N).forEach { y ->
                val sum = (x + 1) + (y + 1)
                val from = c[x][y]
                val cost = D[from -1][to - 1]
                if (sum % 3 == 0) {
                    costZero += cost
                } else if (sum % 3 == 1) {
                    costOne += cost
                } else {
                    costTwo += cost
                }
            }
        }
        zeroMod3Scores[to - 1] = costZero
        oneMod3Scores[to - 1] = costOne
        twoMod3Scores[to - 1] = costTwo
    }

    var minCost = Int.MAX_VALUE
    // O(C^3)
    (0 until C).forEach {i ->
        (0 until C).forEach {j ->
            (0 until C).forEach {k ->
                if (i != j && j != k && k != i) {
                    minCost = Math.min(minCost,
                            zeroMod3Scores[i] + oneMod3Scores[j] + twoMod3Scores[k]
                    )
                }
            }
        }
    }
    println(minCost)
}
