sorted_cnt = sorted(cnt.items(), key=lambda x: (x[1], x[0]))
list(map(list, zip(*A)))
import sys
def cal_R():
max_len = 0; result = []
for i in range(len(A)):
cnt = dict()
for j in range(len(A[i])):
if A[i][j] != 0:
if A[i][j] in cnt:
cnt[A[i][j]] += 1
else:
cnt[A[i][j]] = 1
sorted_cnt = sorted(cnt.items(), key=lambda x: (x[1], x[0]))
if len(sorted_cnt) * 2 > 100:
sorted_cnt = sorted_cnt[:50]
max_len = max(max_len, len(sorted_cnt) * 2)
result.append(sorted_cnt)
final = []
for i in range(len(result)):
tmp = []
for j in range(len(result[i])):
tmp.extend(result[i][j])
for j in range(max_len - len(tmp)):
tmp.append(0)
final.append(tmp)
return final
def cal_C():
max_len = 0; result = []
for j in range(len(A[0])):
cnt = dict()
for i in range(len(A)):
if A[i][j] != 0:
if A[i][j] in cnt:
cnt[A[i][j]] += 1
else:
cnt[A[i][j]] = 1
sorted_cnt = sorted(cnt.items(), key=lambda x: (x[1], x[0]))
if len(sorted_cnt) * 2 > 100:
sorted_cnt = sorted_cnt[:50]
max_len = max(max_len, len(sorted_cnt) * 2)
result.append(sorted_cnt)
final = [[0] * len(A[0]) for _ in range(max_len)]
for i in range(len(result)):
tmp = []
for j in range(len(result[i])):
for k in range(len(result[i][j])):
final[j*2 + k][i] = result[i][j][k]
return final
r, c, k = map(int, sys.stdin.readline()[:-1].split())
A = []
for _ in range(3):
A.append(list(map(int, sys.stdin.readline()[:-1].split())))
# A = cal_R()
# print(A)
# A = cal_R()
# print(A)
# # A = cal_C()
# # print(A)
result_cnt = 0
while True:
if len(A) >= r and len(A[0]) >= c:
if A[r-1][c-1] == k:
break
result_cnt += 1
if result_cnt > 100:
result_cnt = -1; break
if len(A) >= len(A[0]):
A = cal_R()
else:
A = cal_C()
print(result_cnt)