N, M = map(int, input().split()) card = [list(map(int, input().split())) for _ in range(N*M)] IDX = [[-1]*N for _ in range(M)] for i, (n, m) in enumerate(card): IDX[m-1][n-1] = i def func(A): now = -1 idx = 0 cnt = 0 while idx < 5: RANGE = A[idx]-now-1 c = RANGE//(5-idx)+1 cnt += c now += (5-idx)*c while idx < 5 and A[idx] <= now: idx += 1 return cnt-1 ans = 10**18 for i in range(M): for j in range(N-5+1): A = sorted(IDX[i][j:j+5]) ans = min(ans, func(A)) ans = min(ans, func(sorted([IDX[i][0]]+IDX[i][-4:]))) print(ans)