#include #define REP(i,n) for(int i=0;i<(int)(n);i++) #define ALL(x) (x).begin(),(x).end() using namespace std; const int INF = 1e9; int row[1024][1024], column[1024][1024]; vector g[1024000]; int main() { int W, H, N; cin >> W >> H >> N; REP(i,N) { int M; cin >> M; vector B(M+1); REP(j,M+1) cin >> B[j]; REP(j,M) { int a = B[j], b = B[j+1]; if (a > b) swap(a, b); if (b - a < W) { ++row[a/W][a%W]; --row[b/W][b%W]; } else { ++column[a/W][a%W]; --column[b/W][b%W]; } } } REP(i,H) REP(j,W-1) row[i][j+1] += row[i][j]; REP(i,H-1) REP(j,W) column[i+1][j] += column[i][j]; REP(i,H) REP(j,W) { if (row[i][j]) { g[i*W+j].push_back(i*W+j+1); g[i*W+j+1].push_back(i*W+j); } if (column[i][j]) { g[i*W+j].push_back(i*W+j+W); g[i*W+j+W].push_back(i*W+j); } } vector dist(H * W, INF); dist[0] = 0; queue que; que.push(0); while (!que.empty()) { int v = que.front(); que.pop(); for (int i: g[v]) { if (dist[i] < INF) continue; dist[i] = dist[v] + 1; que.push(i); } } //for (int i: dist) cout << i << endl; if (dist[H * W - 1] == INF) cout << "Odekakedekinai.." << endl; else cout << dist[H * W - 1] << endl; return 0; }