from collections import deque def main(): import sys input = sys.stdin.read().split() idx = 0 W = int(input[idx]); idx +=1 H = int(input[idx]); idx +=1 N = int(input[idx]); idx +=1 # Initialize edge matrices h_edges = [[False]*(W-1) for _ in range(H)] # horizontal edges (same row) v_edges = [[False]*W for _ in range(H-1)] # vertical edges (same column) for _ in range(N): M_i = int(input[idx]); idx +=1 B = list(map(int, input[idx:idx+M_i+1])) idx += M_i+1 for j in range(M_i): current = B[j] next_node = B[j+1] x1 = current % W y1 = current // W x2 = next_node % W y2 = next_node // W if y1 == y2: # Same row, process horizontal edges start_x = min(x1, x2) end_x = max(x1, x2) for x in range(start_x, end_x): h_edges[y1][x] = True else: # Same column, process vertical edges start_y = min(y1, y2) end_y = max(y1, y2) for y in range(start_y, end_y): v_edges[y][x1] = True # BFS setup dist = [[-1 for _ in range(W)] for _ in range(H)] q = deque() if W == 0 or H == 0: print("Odekakedekinai..") return dist[0][0] = 0 q.append((0, 0)) found = False while q: x, y = q.popleft() if x == W-1 and y == H-1: print(dist[y][x]) found = True break # Check East if x + 1 < W and h_edges[y][x]: if dist[y][x+1] == -1: dist[y][x+1] = dist[y][x] + 1 q.append((x+1, y)) # Check West if x - 1 >= 0 and h_edges[y][x-1]: if dist[y][x-1] == -1: dist[y][x-1] = dist[y][x] + 1 q.append((x-1, y)) # Check North if y + 1 < H and v_edges[y][x]: if dist[y+1][x] == -1: dist[y+1][x] = dist[y][x] + 1 q.append((x, y+1)) # Check South if y - 1 >= 0 and v_edges[y-1][x]: if dist[y-1][x] == -1: dist[y-1][x] = dist[y][x] + 1 q.append((x, y-1)) if not found: print("Odekakedekinai..") if __name__ == "__main__": main()