#include #include #include #include #include using namespace std; int main() { int w, h, n; cin >> w >> h >> n; vector> row(h, vector(w + 1)); vector> col(h + 1, vector(w)); while (n--) { int m; cin >> m; vector b(m + 1); for (int &bi: b) cin >> bi; for (int i = 0; i < m; i++) { int p0 = b[i], p1 = b[i + 1]; int i0 = p0 / w, j0 = p0 % w; int i1 = p1 / w, j1 = p1 % w; if (i0 == i1) { if (j0 > j1) swap(j0, j1); j1++; row[i0][j0]++; row[i1][j1]--; } else { if (i0 > i1) swap(i0, i1); i1++; col[i0][j0]++; col[i1][j1]--; } } } for (int i = 0; i < h; i++) for (int j = 0; j < w; j++) { row[i][j + 1] += row[i][j]; } for (int j = 0; j < w; j++) for (int i = 0; i < h; i++) { col[i + 1][j] += col[i][j]; } vector> dist(h, vector(w, -1)); queue> que; dist[0][0] = 0; que.emplace(0, 0); while (!que.empty()) { int i, j; tie(i, j) = que.front(); que.pop(); if (row[i][j]) { if (j - 1 >= 0 && row[i][j - 1] && dist[i][j - 1] == -1) { dist[i][j - 1] = dist[i][j] + 1; que.emplace(i, j - 1); } if (j + 1 < w && row[i][j + 1] && dist[i][j + 1] == -1) { dist[i][j + 1] = dist[i][j] + 1; que.emplace(i, j + 1); } } if (col[i][j]) { if (i - 1 >= 0 && col[i - 1][j] && dist[i - 1][j] == -1) { dist[i - 1][j] = dist[i][j] + 1; que.emplace(i - 1, j); } if (i + 1 < h && col[i + 1][j] && dist[i + 1][j] == -1) { dist[i + 1][j] = dist[i][j] + 1; que.emplace(i + 1, j); } } } int res = dist[h - 1][w - 1]; if (res == -1) { cout << "Odekakedekinai.." << endl; } else { cout << res << endl; } return 0; }