import itertools

import collections

h,w = list(map(int,input().split()))

c = [list(map(int,input().split())) for _ in range(10)]

a = [list(map(int,input().split())) for _ in range(h)]

a = list(itertools.chain.from_iterable(a))

b = collections.Counter(a)

ans = 0



def bfs(x):

    if x[-1]==1:

        global s

        buf = 0

        for i in range(len(x)-1):

            buf += c[x[i]][x[i+1]]

        s = min(s,buf)

    else:

        for i in range(10):

            if not i in x:

                bfs(x+[i])



for i in b:

    if not i in [1,-1]:

        s = 10**9

        bfs([i])

        ans += s*b[i]

print(ans)
h,w = list(map(int,input().split()))

c = [list(map(int,input().split())) for _ in range(10)]

a = [list(map(int,input().split())) for _ in range(h)]

n = 10

for k in range(n):

    for i in range(n):

        for j in range(n):

            c[i][j] = min(c[i][j],c[i][k]+c[k][j])

ans = 0

for i in a:

    for j in i:

        if j!=-1: ans += c[j][1]

print(ans)
import itertools
import collections

h, w = list(map(int, input().split()))
c = [list(map(int, input().split())) for _ in range(10)]
a = [list(map(int, input().split())) for _ in range(h)]
a = list(itertools.chain.from_iterable(a))
b = collections.Counter(a)
ans = 0


def bfs(x):
    if x[-1] == 1:
        global s
        buf = 0
        for i in range(len(x) - 1):
            buf += c[x[i]][x[i + 1]]
        s = min(s, buf)
    else:
        for i in range(10):
            if not i in x:
                bfs(x + [i])


for i in b:
    if not i in [1, -1]:
        s = 10**9
        bfs([i])
        ans += s * b[i]
print(ans)

h, w = list(map(int, input().split()))
c = [list(map(int, input().split())) for _ in range(10)]
a = [list(map(int, input().split())) for _ in range(h)]
n = 10
for k in range(n):
    for i in range(n):
        for j in range(n):
            c[i][j] = min(c[i][j], c[i][k] + c[k][j])
ans = 0
for i in a:
    for j in i:
        if j != -1:
            ans += c[j][1]
print(ans)

-import itertools -import collections - -a = list(itertools.chain.from_iterable(a)) -b = collections.Counter(a) +n = 10 +for k in range(n): +    for i in range(n): +        for j in range(n): +            c[i][j] = min(c[i][j], c[i][k] + c[k][j]) - - -def bfs(x): -    if x[-1] == 1: -        global s -        buf = 0 -        for i in range(len(x) - 1): -            buf += c[x[i]][x[i + 1]] -        s = min(s, buf) -    else: -        for i in range(10): -            if not i in x: -                bfs(x + [i]) - - -for i in b: -    if not i in [1, -1]: -        s = 10**9 -        bfs([i]) -        ans += s * b[i] +for i in a: +    for j in i: +        if j != -1: +            ans += c[j][1]