import sys sys.setrecursionlimit(10**6) def scc(N, G, RG): order = [] used = [0]*N group = [None]*N def dfs(s): used[s] = 1 for t in G[s]: if not used[t]: dfs(t) order.append(s) def rdfs(s, col): group[s] = col used[s] = 1 for t in RG[s]: if not used[t]: rdfs(t, col) for i in range(N): if not used[i]: dfs(i) used = [0]*N label = 0 for s in reversed(order): if not used[s]: rdfs(s, label) label += 1 return label, group def construct(N, G, label, group): G0 = [set() for i in range(label)] GP = [[] for i in range(label)] for v in range(N): lbs = group[v] for w in G[v]: lbt = group[w] if lbs == lbt: continue G0[lbs].add(lbt) GP[lbs].append(v) return G0, GP n,m=map(int,input().split()) edge=[[] for i in range(n)] redge=[[] for i in range(n)] for _ in range(m): a,b=map(lambda x:int(x)-1,input().split()) if a==b: print(-1) exit() edge[a].append(b) redge[b].append(a) label,group=scc(n,edge,redge) if label!=n: print(-1) exit() dp=[1]*n G0,GP=construct(n,edge,n,group) for i in range(n): for j in G0[i]: dp[j]=max(dp[j],dp[i]+1) print(max(dp))