import sys readline=sys.stdin.readline w,h,n=map(int,readline().split()) s1=[[0]*w for i in range(h)] s2=[[0]*h for i in range(w)] for i in range(n): m=int(readline()) b=list(map(int,readline().split())) for j in range(m): x1,y1=divmod(b[j],w) x2,y2=divmod(b[j+1],w) if x1==x2: if y1>y2:y1,y2=y2,y1 s1[x1][y1]+=1 s1[x1][y2]-=1 else: if x1>x2:x1,x2=x2,x1 s2[y1][x1]+=1 s2[y1][x2]-=1 from itertools import accumulate for i in range(h):s1[i]=list(accumulate(s1[i])) for i in range(w):s2[i]=list(accumulate(s2[i])) INF=9**9 d=[INF]*h*w d[0]=0 que=[0] for p in que: x, y=divmod(p, w) d0=d[p] p1,p2,p3,p4=(x-1)*w+y,(x+1)*w+y,x*w+y-1,x*w+y+1 if x-1>=0and s2[y][x-1]and d[p1]>d0+1: d[p1]=d0+1 que.append(p1) if x+1d0+1: d[p2]=d0+1 que.append(p2) if y-1>=0and s1[x][y-1]and d[p3]>d0+1: d[p3]=d0+1 que.append(p3) if y+1d0+1: d[p4]=d0+1 que.append(p4) print(d[-1]if d[-1]