N,M=map(int,input().split()) v=[[[] for i in range(N+1)] for j in range(M+1)] for i in range(N*M): n,m=map(int,input().split()) l=n-4 if l<=0: l=1 for x in range(l,n+1): v[m][x].append(i+1) if n==1: v[m][N-3].append(i+1) result=10**9 for i in range(1,M+1): for j in range(1,N-2): a,b,c,d,e=v[i][j][:] count=0 x=0 for k in range(5): a=v[i][j][k] if a<=x: continue e=(a-x+4-k)//(5-k) x+=e*(5-k) count+=e result=min(result,count-1) print(result)