import sys from collections import deque input = sys.stdin.buffer.readline def solve(N: int, K: int, G: list[list[int]]): deg = [0] * N for i in range(N): for j in G[i]: deg[j] += 1 q = deque(v for v in range(N) if deg[v] == 0) visited = [False] * N max_chain = [1] * N while q: v = q.popleft() if visited[v]: continue visited[v] = True for t in G[v]: deg[t] -= 1 max_chain[t] = max(max_chain[t], max_chain[v] + 1) if deg[t] == 0: q.append(t) if max(deg) == 0: return max(max_chain) else: return -1 N, K = map(int, input().split()) G = [[] for _ in range(N)] deg = [0] * N for _ in range(K): r, c = map(lambda x: int(x) - 1, input().split()) G[r].append(c) print(solve(N, K, G))