Revenge of the Endless BFS

Decide whether a buggy BFS that forgets visited vertices ever terminates on a given directed graph, and if so output the loop count modulo 1e9+7.

Hard9GraphBFSMathDynamic programmingNo attempts yetTime limit2sMemory limit512 MB

Problem

Mr. Endo wanted to write code that performs breadth-first search (BFS), a search algorithm that explores every vertex of a directed graph. An example of BFS in pseudo code follows.

1: current ← {start_vertex}
2: visited ← current
3: while visited ≠ the set of all the vertices
4:   found ← {}
5:   for u in current
6:     for each v such that there is an edge from u to v
7:       found ← found ∪ {v}
8:   current ← found ∖ visited
9:   visited ← visited ∪ found

However, Mr. Endo apparently forgot to manage the visited vertices in his code. More precisely, he wrote the following code.

1: current ← {start_vertex}
2: while current ≠ the set of all the vertices
3:   found ← {}
4:   for u in current
5:     for each v such that there is an edge from u to v
6:       found ← found ∪ {v}
7:   current ← found

For some graphs, Mr. Endo's program never stops and keeps running forever. Note that this does not necessarily mean the program cannot explore all the vertices within a finite number of steps. To point out the bug to him, write a program that decides whether Mr. Endo's program stops within a finite number of steps for a given directed graph. If it stops, also compute the minimum number of loop iterations the program needs before it stops. Since the answer might be huge, print it modulo 109+710^9 + 7, which is a prime number.

Input

The input consists of a single test case in the following format.

N M
u1 v1
.
.
.
uM vM

The first line contains two integers NN (2N5002 \le N \le 500) and MM (1M200,0001 \le M \le 200{,}000), where NN is the number of vertices and MM is the number of edges of the directed graph. The ii-th of the following MM lines contains two integers uiu_i and viv_i (1ui,viN1 \le u_i, v_i \le N), which means there is an edge from uiu_i to viv_i. Vertex 1 is the start vertex, that is, start_vertex in the pseudo code. The given graph also satisfies the following conditions.

  • The graph has no self-loop, that is, uiviu_i \ne v_i for all 1iM1 \le i \le M.
  • The graph has no multi-edge, that is, (ui,vi)(uj,vj)(u_i, v_i) \ne (u_j, v_j) for all 1i<jM1 \le i < j \le M.
  • For each vertex vv, there is at least one path from the start vertex 1 to vv.

Output

If Mr. Endo's wrong BFS code cannot stop within a finite number of steps for the given directed graph, print -1 on a line. Otherwise, print the minimum number of loop iterations needed before it stops, modulo 109+710^9 + 7.