#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>#include <algorithm>#include <vector>using namespace std;int P, Q, R, QR, PQR;int a[100], h, locE;int Limit;bool out(int x){ return x < 0 || x >= PQR;}int dis(int id1, int id2){ int x = id1/QR, x2 = id2/QR; id1 %= QR; id2 %= QR; int y = id1/R, y2 = id2/R; id1 %= R; id2 %= R; return abs(x-x2) + abs(y-y2) + abs(id1-id2);}#define DFSTT { int td = dis(locE, a[ll]) - dis(ll, a[ll]); swap(a[ll], a[locE]); h += td; locE = ll; bool found = dfs(th+1); locE = tE; h -= td; swap(a[ll], a[locE]); if(found) return true;}bool dfs(int th){ if(h == 0) return true; if(th+h > Limit) return false; int x = locE/QR, y = locE%QR/R, z = locE%R, tE = locE; if(x > 0){ int ll = locE - QR; DFSTT; } if(x < P - 1){ int ll = locE + QR; DFSTT; } if(y > 0){ int ll = locE - R; DFSTT; } if(y < Q - 1){ int ll = locE + R; DFSTT; } if(z > 0){ int ll = locE - 1; DFSTT; } if(z < R - 1){ int ll = locE + 1; DFSTT; } return false;}int main() { while(scanf("%d%d%d", &P, &Q, &R) != EOF){ QR = Q*R; PQR = P*QR; if(PQR == 0) while(1); for(int i = 0; i < PQR; i ++){ scanf("%d", &a[i]); a[i] --; } Limit = 0; h = 0; int sum = 0; for(int i = 0; i < PQR; i ++) for(int j = i + 1; j < PQR; j ++) if(a[i] > a[j]) sum ++; for(int i = 0; i < PQR; i ++){ if(a[i] != PQR-1) h += dis(a[i], i); else{ locE = i; sum += dis(a[i], i); } } if(sum&1){ printf("-1n"); continue; } while(!dfs(0)){ Limit ++; } printf("%dn", Limit); } return 0;}


