#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
typedef pair<int, int> pii;
int r, c, k, m[101][101], cnt[101], rnum = 3, cnum = 3;
map<int, int> mp;
vector<pii> v;
bool cmp(pii a, pii b) {
if (a.second < b.second) return true;
else if (a.second == b.second) {
return a.first < b.first;
}
else return false;
}
void rOpr() {
int curC = cnum; //연산 중간에 행길이를 갱신할 것이기 때문에 시작값 저장
for (int i = 1; i <= rnum; i++) {
for (int j = 1; j <= curC; j++) {
if (m[i][j] == 0) continue;
mp[m[i][j]]++;
}
for (map<int, int>::iterator itr = mp.begin(); itr != mp.end(); itr++)
v.push_back({ itr->first, itr->second });
sort(v.begin(), v.end(), cmp);
int vSize = v.size();
if (v.size() >= 50) vSize = 50; //100개까지만 취하도록
for (int j = 0; j < vSize; j++) {
m[i][2*j+1] = v[j].first;
m[i][2*j+2] = v[j].second;
}
for (int j = vSize * 2 + 1; j <= curC; j++)
m[i][j] = 0; // 원래 길이보다 짧아지면, 이전 것을 0으로 만들어줘야 함
if (cnum < vSize * 2) cnum = vSize * 2; //최대 길이 갱신
mp.clear();
v.clear();
}
}
void cOpr() {
int curR = rnum;
for (int i = 1; i <= cnum; i++) {
for (int j = 1; j <= curR; j++) {
if (m[j][i] == 0) continue;
mp[m[j][i]]++;
}
for (map<int, int>::iterator itr = mp.begin(); itr != mp.end(); itr++)
v.push_back({ itr->first, itr->second });
sort(v.begin(), v.end(), cmp);
int vSize = v.size();
if (v.size() >= 50) vSize = 50;
for (int j = 0; j < vSize; j++) {
m[2 * j + 1][i] = v[j].first;
m[2 * j + 2][i] = v[j].second;
}
for (int j = vSize * 2 + 1; j <= curR; j++)
m[j][i] = 0;
if (rnum < vSize * 2) rnum = vSize * 2;
mp.clear();
v.clear();
}
}
int main(void) {
cin >> r >> c >> k;
for (int i = 1; i <= 3; i++)
for (int j = 1; j <= 3; j++)
cin >> m[i][j];
int time = 0;
for (time = 0; time <= 100; time++) {
if (m[r][c] == k) break; //종료 조건
if (rnum >= cnum) //r연산
rOpr();
else
cOpr();
}
if (time == 101) cout << -1;
else cout << time;
return 0;
}