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)] visited = [False for i in range(n+1)] for i in range(1,n+1): if not check[i]: que = [(i,0)] while que: now, inout = que.pop() if inout == 0: if not check[now]: check[now] = True que.append((now,1)) visited[now] = True for j in g[now]: if visited[j]: print(-1) exit() que.append((j,0)) else: visited[now] = False 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)] while que: now, inout = que.pop() if inout == 0: if not check[now]: check[now] = True que.append((now,1)) for j in g[now]: 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))