N,M = map(int, input().split())
NM = [list(map(int, input().split())) for _ in range(N*M)]
ans = 10**10
for i in range(1,M+1):
    cnt = 0
    hand = 0
    card = 5
    for n,m in NM[:5]:
        if m==i and (n==1 or n>=N-3):
            hand+=1
    while hand<5:
        for n,m in NM[card:card+5-hand]:
            if m==i and (n==1 or n>=N-3):
                hand+=1
            card+=1
        cnt+=1
    ans = min(cnt,ans)
print(ans)