All problems

Problem 431

Minimum Edge Reversals

Hard · 30 pts · Graph, Breadth-First Search, Shortest Path

Problem

A directed graph has N nodes labelled 1 to N. You want to travel from node 1 to node N along the direction of the edges, and you are allowed to reverse some edges first. Find the minimum number of edges you must reverse, or -1 if node N cannot be reached even with reversals. Model it as a shortest-path problem: following an edge costs 0 and going against it costs 1. With only weights 0 and 1, a deque-based '0-1 BFS' solves it in linear time.

Input

First line: N and M. Next M lines: a directed edge u v (from u to v).

Output

Print the minimum number of reversals, or -1.

Constraints

1 <= N <= 100000; 0 <= M <= 200000

Example input

4 3
1 2
3 2
3 4

Example output

1

Explanation

With edges 1→2, 3→2 and 3→4, going from 1 to 4 needs the path 1 → 2 → 3 → 4. The edge 3→2 points the wrong way, so one reversal is needed.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: City with the Fewest Reachable Neighbours Next: Minimum Cost to Connect Points