import sys readline = sys.stdin.readline w,h,n = map(int,input().split()) b1 = [[0]*w for _ in range(h)] b2 = [[0]*h for _ in range(w)] for _ in range(n): m = int(readline()) t = list(map(int,input().split())) for i in range(m): x,y = t[i],t[i+1] if x > y: x,y = y,x if abs(x-y) < w: b1[x//w][x%w] += 1 b1[y//w][y%w] -= 1 else: b2[x%w][x//w] += 1 b2[y%w][y//w] -= 1 for i in range(h): for j in range(1,w): b1[i][j] += b1[i][j-1] for j in range(w): for i in range(1,h): b2[j][i] += b2[j][i-1] from collections import deque q = deque([(0,0)]) b = [[-1]*w for _ in range(h)] b[0][0] = 0 while q: vi,vj = q.popleft() d = b[vi][vj] if vj and b1[vi][vj-1] and b[vi][vj-1]==-1: b[vi][vj-1] = d+1 q.append((vi,vj-1)) if vj+1