#include using namespace std; typedef long long int ll; typedef pair P; typedef pair Pll; typedef vector Vi; //typedef tuple T; #define FOR(i,s,x) for(int i=s;i<(int)(x);i++) #define REP(i,x) FOR(i,0,x) #define ALL(c) c.begin(), c.end() #define DUMP( x ) cerr << #x << " = " << ( x ) << endl const int dr[4] = {-1, 0, 1, 0}; const int dc[4] = {0, 1, 0, -1}; #define INF 1000010 // graph by adjacency list struct Edge { int dst; Edge(int dst) : dst(dst) { } }; vector E[1000010]; struct Graph { int V; Graph(int V) : V(V) { } void add_edge(int src, int dst) { E[src].push_back(Edge(dst)); } }; struct Node { int v, dist; Node(int v, int dist) : v(v), dist(dist) { }; bool operator < (const Node &n) const { return dist > n.dist; // reverse } }; int dist[1000010]; struct ShortestPath { const Graph g; int start; ShortestPath(const Graph g, int start) : g(g), start(start) { } inline void dijkstra(int goal) { queue que; dist[start] = 0; que.push(Node(start, 0)); while (!que.empty()) { Node n = que.front(); que.pop(); int v = n.v, cost = n.dist; if (v == goal) return ; if (dist[v] < cost) continue; cost++; REP(i, E[v].size()) { Edge e = E[v][i]; if (e.dst and not dist[e.dst]) { dist[e.dst] = cost; if (e.dst == goal) return ; que.push(Node(e.dst, cost)); } } } } }; int imos_w[1000010], imos_h[1000010]; int main() { int W, H, N; scanf("%d%d%d", &W, &H, &N); REP(i, N) { int M, prev; scanf("%d%d", &M, &prev); REP(i, M) { int b; scanf("%d", &b); int p1 = prev, p2 = b; if (p1 > p2) swap(p1, p2); int r1 = p1 / W, c1 = p1 % W, r2 = p2 / W, c2 = p2 % W; //cout << '(' << r1 << ',' << c1 << ')' << ' ' << '(' << r2 << ',' << c2 << ')' << endl; if (r1 == r2) { imos_w[p1]++, imos_w[p2]--; } else if (c1 == c2) { imos_h[c1 * H + r1]++, imos_h[c2 * H + r2]--; } prev = b; } } REP(i, W*H-1) imos_h[i+1] += imos_h[i], imos_w[i+1] += imos_w[i]; Graph g(H*W); REP(i, H*W) { if (imos_w[i]) g.add_edge(i, i+1), g.add_edge(i+1, i); if (imos_h[i]) { int p1 = (i%H)*W+i/H, p2 = p1 + W; g.add_edge(p1, p2), g.add_edge(p2, p1); } } /*REP(i, W*H) { cout << i << ':'; for (auto v : g.E[i]) cout << v.dst << ' '; cout << endl; }*/ ShortestPath sp(g, 0); sp.dijkstra(W*H-1); if (W*H-1 and dist[W*H-1] == 0) { printf("Odekakedekinai..\n"); } else { printf("%d\n", dist[W*H-1]); } //REP(i, g.V) cout << sp.dist[i] << (i == g.V-1 ? '\n' : ' '); return 0; }