Endless BFS
Time limit2sMemory limit512 MB
Run a BFS that forgets visited vertices, so the active set alternates between bipartition classes. Decide whether it ever equals all vertices and report the least step when it does.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Implementation, Simulation
- Solved
- No attempts yet
Problem
Mr. Endo wanted to write code that performs breadth-first search (BFS), a search algorithm that explores all vertices of an undirected graph. An example of BFS pseudo code is as follows:
1: $current \leftarrow \{start\_vertex\}$
2: $visited \leftarrow current$
3: while $visited \ne$ the set of all the vertices
4: $found \leftarrow \{\}$
5: for $v$ in $current$
6: for each $u$ adjacent to $v$
7: $found \leftarrow found \cup \{u\}$
8: $current \leftarrow found \setminus visited$
9: $visited \leftarrow visited \cup found$
However, Mr. Endo apparently forgot to manage visited vertices in his code. More precisely, he wrote the following code:
1: $current \leftarrow \{start\_vertex\}$
2: while $current \ne$ the set of all the vertices
3: $found \leftarrow \{\}$
4: for $v$ in $current$
5: for each $u$ adjacent to $v$
6: $found \leftarrow found \cup \{u\}$
7: $current \leftarrow found$
You may notice that for some graphs, Mr. Endo's program will not stop because it keeps running infinitely. Notice that this does not necessarily mean the program cannot explore all the vertices within finitely many steps. See example 2 below for more details. Your task here is to make a program that determines whether Mr. Endo's program will stop within finitely many steps for a given graph in order to point out the bug to him. Also, calculate the minimum number of loop iterations required for the program to stop if it is finite.
Input
The input consists of a single test case formatted as follows.
$N$ $M$
$U_{1}$ $V_{1}$
$\vdots$
$U_{M}$ $V_{M}$
The first line consists of two integers () and (), where is the number of vertices and is the number of edges in the given undirected graph. The -th line of the following lines consists of two integers and (), which means the vertices and are adjacent in the given graph. Vertex 1 is the start vertex, i.e. in the pseudo codes. You can assume that the given graph also meets the following conditions.
- The graph has no self-loop, i.e., for all .
- The graph has no multi-edge, i.e., for all .
- The graph is connected, i.e., there is at least one path from to (and vice versa) for all vertices .
Output
If Mr. Endo's wrong BFS code cannot stop within finitely many steps for the given input graph, print -1 on a line. Otherwise, print the minimum number of loop iterations required to stop.