Your life
InterviewTime limit1sMemory limit256 MB
Find the fewest directed moves from node 1 to node N in a graph where every edge goes forward, or report -1 when the goal is unreachable.
- Level
Easy3 of 10
- Topics
- BFS, Shortest path, Graph
- Solved
- No attempts yet
Problem
The situations you can run into while chasing a dream are drawn as a graph. All of them are compressed into situations numbered 1 to . You are in situation 1 right now, and situation is the single dream you want to reach.
A situation changes according to your choice. There are changes you can choose from, each given as a pair , . It means that while you are in situation you may choose to move to situation , and is guaranteed.
Can you reach the dream? If you can, how many changes does it take when you keep the number of changes as small as possible?
Input
The first line contains the natural numbers and separated by a space, where and .
Each of the next lines contains the natural numbers and separated by a space, where . The same change may be given more than once.
Output
If you can reach the dream, print the minimum number of situation changes it takes. Otherwise print -1.
Hint
In the first example you move from situation 1 to situation 2 and then from situation 2 to situation 4, so two changes are enough.