n,m=map(int,input().split()) c=[[0]*(n+1) for i in range(m)] for i in range(n*m): s,t=map(int,input().split()) s-=1 t-=1 c[t][s]=max(0,i-4) if s==0: c[t][n]=max(0,i-4) a=n*m for i in range(m): for j in range(n-3): g=c[i][j:j+5] g.sort() b=0 bb=0 for k in range(5): if g[k]<=bb: continue b+=(g[k]-bb+5-k-1)//(5-k) bb+=(g[k]-bb+5-k-1)//(5-k)*(5-k) a=min(a,b) print(a)