from collections import defaultdict import sys N, K = map(int, input().split()) graph = defaultdict(list) for _ in range(K): r, c = map(lambda x:int(x)-1, input().split()) graph[r].append(c) memo = [0] * (N+1) seen = [False] * (N+1) sys.setrecursionlimit(1000000) def dfs(v): if memo[v]: return memo[v] seen[v] = True res = 1 for next_v in graph[v]: if seen[next_v] and not memo[next_v]: print(-1) sys.exit() res = max(res, dfs(next_v)+1) memo[v] = res return res for i in range(N): if memo[i]: continue dfs(i) print(max(memo))