
fun main(args:Array<String>) {
    val (H,W) = readLine()!!.split(" ").map(String::toInt)
    val power = 0.until(10).map {
        readLine()!!.split(" ").map(String::toInt)
    }

    val A = (1..H).map{
        val row = readLine()!!.split(" ").map(String::toInt)
        assert(row.size == W)
        row
    }

    var costs = Array(10) {i-> Array(10) {j-> power[i][j]}}
    for(i in 0..9) {
        for(j in 0..9) {
            for(k in 0..9) {
                costs[j][k] = arrayOf(costs[j][k],costs[j][i]+costs[i][k]).min()!!
            }
        }
    }
    val min_costs = Array(10) {costs[it][1]}
    // min_costs.joinToString(",").let(::println)
    A.fold(0L) {sum,row -> 
    sum + row
    .filter{it != -1}
    .fold(0L) {acc,index->
        acc + min_costs[index]
    }}.let {
        println(it)
    }
}
