import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import kotlin.math.min

val br = BufferedReader(InputStreamReader(System.`in`))
val out = PrintWriter(System.out)

fun main() {
    br.use { out.use {
        solve()
        out.flush()
    } }
}

fun solve() {
    val (n, c) = readIntegerList()
    val changeCostArrays = Array(c) { readIntegerList() }
    val colorArrays = Array(n) { readIntegerList().map { it - 1 } }

    val changeCosts = Array(3) { IntArray(c) }
    for (h in 0 until n) {
        for (w in 0 until n) {
            val index = (h + w) % 3
            val currentColor = colorArrays[h][w]
            for (color in 0 until c) {
                changeCosts[index][color] += changeCostArrays[currentColor][color]
            }
        }
    }

    var ans = Int.MAX_VALUE
    for (c1 in 0 until c) {
        for (c2 in 0 until c) {
            for (c3 in 0 until c) {
                if (c1 != c2 && c2 != c3 && c3 != c1) {
                    ans = min(ans, changeCosts[0][c1] + changeCosts[1][c2] + changeCosts[2][c3])
                }
            }
        }
    }
    out.println(ans)
}

fun readInteger() = Integer.parseInt(br.readLine())
fun readLong() = java.lang.Long.parseLong(br.readLine())
fun readStringList() = br.readLine()!!.split(' ')
fun readIntegerList() = readStringList().map(Integer::parseInt)
fun readLongList() = readStringList().map(java.lang.Long::parseLong)
fun readDoubleList() = readStringList().map(java.lang.Double::parseDouble)
