import core.bitop;
import std.algorithm;
import std.ascii;
import std.bigint;
import std.conv;
import std.functional;
import std.math;
import std.numeric;
import std.range;
import std.stdio;
import std.string;
import std.random;
import std.typecons;
import std.container;

enum MAX = 1_000_100;
ulong MOD = 1_000_000_007;
ulong INF = 1_000_000_000_000;
alias sread = () => readln.chomp();
alias Pair = Tuple!(long, "cost", long, "num");
alias PQueue(T, alias less = "a<b") = BinaryHeap!(Array!T, less);

void main()
{
    long h, w;
    scan(h, w);
    auto change = new long[][](10, 10);
    foreach (ref e; change)
        e = aryread();
    auto wall = new long[][](h, w);
    foreach (ref e; wall)
        e = aryread();
    auto magic_power = new long[](10);
    magic_power[] = INF, magic_power[1] = 0;
    auto sl = (iota(10)).SList!long;
    sl.linearRemoveElement(1);
    while (!sl.empty)
    {
        auto p = new Pair[](0);
        foreach (e; sl)
        {
            long cost = INF;
            foreach (i; iota(10))
            {
                cost = min(change[e][i] + magic_power[i], cost);
            }
            p ~= Pair(cost, e);
        }
        p.sort!"a.cost<b.cost"();
        magic_power[p[0].num] = p[0].cost;
        sl.linearRemoveElement(p[0].num);
    }
    long ans;
    foreach (i; iota(h))
        foreach (j; iota(w))
            ans += magic_power[abs(wall[i][j])];
    ans.writeln();
}

T lread(T = long)()
{
    return readln.chomp.to!T();
}

T[] aryread(T = long)()
{
    return readln.split.to!(T[])();
}

void scan(TList...)(ref TList Args)
{
    auto line = readln.split();
    foreach (i, T; TList)
    {
        T val = line[i].to!(T);
        Args[i] = val;
    }
}
