N, M = map(int, input().split()) NM = [list(map(int, input().split())) for _ in range(N*M)] dp = [[0 for _ in range(N+1)] for _ in range(M)] for i in range(5): n, m = NM[i] n-=1 m-=1 dp[m][n] = 1 if n==0: dp[m][N] = 1 cnt = 1 for i in range(5, N*M): n, m = NM[i] n-=1 m-=1 dp[m][n] = cnt+1 if n==0: dp[m][N] = cnt+1 cnt+=1 #print(dp) INF = N*M ans = INF for i in range(M): for j in range(N): S = [] flag = True for k in range(j, j+5): if 0<=k<=N: S.append(dp[i][k]) else: flag = False break if flag: S.sort() tmp = 0 st = 1 a = S.count(st) while S[-1]>st: tmp+=1 st+=(5-a) for idx in range(a, 5): if S[idx]>st: a = idx-1 break #print(S, tmp) ans = min(ans, tmp) print(ans)