#include #include #include #include #include #include #include using namespace std; int dx[4] = { 0,1,0,-1 }; int dy[4] = { 1,0,-1,0 }; int hori[2000][2000], vert[2000][2000]; int dist[1010101]; int main() { int h, w, n; cin >> h >> w >> n; for (int i = 0; i < n; i++) { int m; cin >> m; int b; cin >> b; int x, y, xx, yy; x = b / w; y = b % w; while (m--) { cin >> b; xx = b / w; yy = b % w; if (x == xx) { hori[x][min(y, yy)]++; hori[x][max(y, yy) + 1]--; } else { vert[min(x, xx)][y]++; vert[max(x, xx) + 1][y]--; } x = xx; y = yy; } } for (int i = 0; i < h; i++) for (int j = 0; j < w; j++)hori[i][j + 1] += hori[i][j]; for (int i = 0; i < w; i++) for (int j = 0; j < h; j++)vert[j + 1][i] += vert[j][i]; for (int i = 0; i < w * h; i++)dist[i] = -1; dist[0] = 0; queue que; que.push(0); auto toID = [&](int a, int b) { return a * w + b; }; auto push = [&](int a, int b, int d) { int id = toID(a, b); if (dist[id] == -1) { dist[id] = d; que.push(id); } }; while (!que.empty()) { int s = que.front(); que.pop(); int x, y; x = s / w; y = s % w; if (x && vert[x][y] && vert[x - 1][y])push(x - 1, y, dist[s] + 1); if (y && hori[x][y] && hori[x][y - 1])push(x, y - 1, dist[s] + 1); if (x + 1 < h && vert[x][y] && vert[x + 1][y])push(x + 1, y, dist[s] + 1); if (y + 1 < w && hori[x][y] && hori[x][y + 1])push(x, y + 1, dist[s] + 1); } if (dist[h * w - 1] == -1) cout << "Odekakedekinai.." << endl; else cout << dist[h * w - 1] << endl; return 0; }