using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// using System.Numerics;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using ll=System.Int64;
using static Contest_D.Lib_IO;
using static Contest_D.Lib_Minifunc;
public static class Contest_D
{
public static void Main() {
checked{
long w,h,n,dum;
Lib_IO.rm(out w,out h, out n);
ll[][] b = new ll[n][];
for (int i = 0; i < n; i++)
{
rm(out dum);
ra(out b[i]);
}
bool[][] g = initm(h,w,false);
bool[][] v = initm(h*w,h*w,false);
List
> edge = new List
>();
foreach (var e in b)
{
for (int i = 0; i < e.Length-1; i++)
{
ll x1 = e[i]%w;
ll y1 = e[i]/w;
ll x2 = e[i+1]%w;
ll y2 = e[i+1]/w;
if(x1==x2){
if(y1(k*w+x1,(k+1)*w+x1,1));
}
}
}else{
for (int k = (int)y2; k < y1; k++) {
g[k][x1] = true;
if(!v[k*w+x1][(k+1)*w+x1]){
v[k*w+x1][(k+1)*w+x1] = true;
v[(k+1)*w+x1][k*w+x1] = true;
edge.Add(new P(k*w+x1,(k+1)*w+x1,1));
}
}
}
}else{
if(x1(y1*w+k,y1*w+k+1,1));
}
}
}else{
for (int k = (int)x2; k < x1; k++) {
g[y1][k] = true;
if(!v[y1*w+k][y1*w+k+1]){
v[y1*w+k][y1*w+k+1] = true;
v[y1*w+k+1][y1*w+k] = true;
edge.Add(new P(y1*w+k,y1*w+k+1,1));
}
}
}
}
}
}
ll[] pr;
var rt = Dijkstra(edge.ToArray(), h*w, 0, out pr);
Lib_IO.wm(int.MaxValue