fun main(args : Array<String>){
    val (n,c) = readLine()!!.split(' ').map(String::toInt)
    val d = mutableListOf<List<Int>>()
    for(i in 0 until c){
        val tmp = readLine()!!.split(' ').map(String::toInt)
        d.add(tmp)
    }
    val mp = mutableListOf<List<Int>>()
    for(i in 0 until n){
        val tmp = readLine()!!.split(' ').map(String::toInt)
        mp.add(tmp)
    }

    val seica = Array(3,{IntArray(55,{0})})

    for(i in 0 until n){
        for(j in 0 until n){
            seica[(i+j)%3][mp[i][j]-1]++
        }
    }

    var ans = 1000000000

    for(i in 0 until c){
        for(j in 0 until c){
            for(k in 0 until c){
                if(i == j || j == k || k == i)continue
                var tmp = 0
                for(x in 0 until c){
                    tmp += seica[0][x] * d[x][i]
                    tmp += seica[1][x] * d[x][j]
                    tmp += seica[2][x] * d[x][k]
                }
                ans = Math.min(ans,tmp)
            }
        }
    }

    println(ans)

}