from sys import stdin n, m, *indata = map(int, stdin.read().split()) offset = 0 g = [[] for i in range(n+1)] for i in range(m): s, t = indata[offset + 2*i],indata[offset + 2*i+1] g[s].append(t) check = [False for i in range(n+1)] for i in range(1,n+1): if not check[i]: que = [(i,0)] visited = set() while que: now, inout = que.pop() if inout == 0: if not check[now]: check[now] == True que.append((now,1)) visited.add(now) for j in g[now]: if j in visited: print(-1) exit() que.append((j,0)) else: visited.remove(now) dp = [0 for i in range(n+1)] check = [False for i in range(n+1)] for i in range(1,n+1): if not check[i]: que = [(i,0)] check[i] = True while que: now, inout = que.pop() if inout == 0: que.append((now,1)) for j in g[now]: if not check[j]: que.append((j,0)) else: for j in g[now]: dp[now] = max(dp[now],dp[j]+1) ans = max(dp) + 1 print("{}".format(ans))