We are given a directed graph with N vertices and M edges. We want to find the minimum number of edge reversals needed so that there is at least one directed path from vertex 1 to vertex N. We can reverse any edges; each reversal counts as 1 cost. We need the minimum total number of reversals required to achieve a directed path from 1 to N.
Interpretation: We have original directed edges. We are allowed to reverse some edges (i.e., change direction) at cost 1 per edge. We want to transform the graph into a new directed graph where there exists a directed path from 1 to N. We can also possibly use edges in original direction without cost. The goal is to minimize number of reversals.
This is a classic problem: find the shortest path where each edge has weight 0 if we traverse it in its original direction, and weight 1 if we traverse it opposite to its direction (i.e., we need to reverse it). But careful: The path we consider after reversals: we will reverse some edges, and then we want a directed path from 1 to N in the resulting graph. That is equivalent to choosing a directed path from 1 to N in the original graph if we are allowed to reverse edges along the path? Actually, if we reverse some edges, we can then traverse them in the new direction. But note that reversals affect the entire graph, not only the path. However, if we only care about existence of a directed path from 1 to N after reversals, we can think of picking a set of edges to reverse such that after reversal there is a directed path. The minimal number of reversals will be achieved by reversing only edges that are used in the path in the opposite direction, while keeping others unchanged. Because any reversal not on the path doesn't help create a path from 1 to N, unless needed to connect something? But we can choose a directed path from 1 to N in the transformed graph. In the transformed graph, each edge either kept as original or reversed. If we consider any directed path from 1 to N after reversals, then for each edge on that path, if it's oriented in the same direction as needed for the path, that edge either is original direction (cost 0) or was reversed (cost 1) if originally opposite. Thus, the path corresponds to a sequence of edges from 1 to N where we pay cost 1 for each edge that we need to reverse to make it point along the path direction. So the minimal number of reversals needed is exactly the length (in terms of number of edges) of a path from 1 to N in a graph where each directed edge (u->v) we consider has weight 0 if that direction exists originally, and weight 1 if the opposite direction exists originally? Wait careful.
We have original directed edges. Suppose we pick a directed path from 1 to N in the final graph: vertices v0=1, v1, v2,..., vk=N. For each step from vi to vi+1, we need an edge oriented from vi to vi+1. In the original graph, there may or may not be an edge from vi to vi+1. If there is, we can use it without reversing. If there is not, but there is an edge from vi+1 to vi, we can reverse it to make it from vi to vi+1 (cost 1). However, could we use an edge that is not originally present at all? No, we can only reverse existing edges; we cannot create new edges. So for each consecutive pair (a,b) on the path, we require that either there is a directed edge a->b (original) or there is a directed edge b->a (original) which we can reverse to get a->b. If neither exists, that step is impossible. Thus, the problem reduces to: In a graph where we have all possible pairs? Actually, we can think of constructing a new graph with same vertices, and for each original directed edge (u,v) we allow two possibilities: going from u to v with cost 0, and going from v to u with cost 1 (reversal). But note: original edge (u,v) can be used in forward direction (u->v) at cost 0, and also in reverse direction (v->u) at cost 1. This transforms the problem into finding the shortest path from 1 to N in this new graph where each edge has weight 0 or 1. Since weights are 0/1, we can use 0-1 BFS (deque) to compute shortest distance. The answer is that distance, or -1 if unreachable.
But caution: The original graph may have multiple edges and self loops. However, self loops (u->u) can never be part of a simple path? Actually, they could be used, but they wouldn't help to go from 1 to N because they don't change vertex. In path, we might include them but that would increase cost and not progress. They can be ignored for shortest path since they are cycles that don't help. But for completeness, they are edges. For a self loop u->u, we can traverse from u to u at cost 0, but that doesn't change vertex; similarly reverse would be same direction? Reversing a self loop doesn't change it. So it's irrelevant. However, including them in the graph for 0-1 BFS may cause infinite loops? But we can handle: for a self loop, we add edge (u,u) with weight 0, and also possibly weight 1 if considered reverse? Actually, reversing a self loop is the same as original, so it's the same. But we can just ignore them because they don't help.
Also, multiple edges: we treat each separately. So for each original edge (u,v), we add a directed edge from u to v with weight 0, and a directed edge from v to u with weight 1. That's it.
Then we run 0-1 BFS from source 1 to compute min cost to reach each node. The distance to N is answer, if finite; else -1.
Complexities: O(N+M) essentially with deque.
But wait: Is it always optimal to only reverse edges on a single path? Could there be a scenario where reversing some edge not on the path reduces the number of reversals needed? For example, maybe by reversing an edge not on the path, you can create a shortcut that reduces the number of reversals on the path? But that would be captured by the 0-1 BFS model because we consider all possible traversals where each step corresponds to either using an original edge (cost 0) or its reverse (cost 1). In this graph, a path from 1 to N corresponds to a sequence of vertices where each step uses either an original edge in its original direction or an original edge reversed. This exactly corresponds to a final graph where we reverse exactly those edges that were traversed in reverse direction. No other edges are reversed. So indeed the optimal solution is to find such a path minimizing number of reversals.
But there is nuance: What if we need to reverse an edge that is used in both directions? Not possible because after reversal, the edge direction is fixed. In our path, we may need to reverse an edge that we also want to use in original direction elsewhere? But we are only constructing one path; after reversals, the graph may have other edges reversed as well, but they are not needed. However, could reversing an edge that is not on the path cause a conflict for the path? No, because we are only concerned about existence of a path. If we reverse an extra edge, it could only potentially create additional paths, but doesn't harm the existing path. So minimal cost solution won't reverse unnecessary edges.
Thus, 0-1 BFS works.
But wait: The problem statement: "minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to vertex N." That's exactly the interpretation.
Now constraints: N, M up to 100000, so 0-1 BFS is fine.
Implementation details:
-
We'll read N, M.
-
For each edge (x, y):
- if x != y:
add edge (x, y) with weight 0.
add edge (y, x) with weight 1.
- else: self-loop: can ignore (or add with weight 0, but it might cause infinite loops if we allow relaxation from u to u with cost 0? Actually, in 0-1 BFS, when we process node u, we might see edge to u with weight 0, that would relax distance to u to same distance; it's okay but could cause infinite relaxation loops if we push again? Typically we only push if distance improves. Distance to u is same as current, so it wouldn't improve, so no push. So safe to add, but unnecessary. We'll ignore for simplicity.)
-
Then we need to run 0-1 BFS from node 1. Use deque. Distance array initialized to INF (e.g., large number). dist[1]=0. deque.push_front(1). While deque not empty: pop front u. For each neighbor (v, w) in adjacency list[u]: if dist[u] + w < dist[v]: update dist[v]; if w==0: push front; else push back.
-
After BFS, if dist[N] is INF, output -1, else output dist[N].
But we must be careful: The graph may be large, adjacency list with up to 2M edges (since we add two directed edges per original edge). M up to 1e5, so 2e5 edges, fine.
Check example: Input:
7 7
1 2
3 2
3 4
7 4
6 2
5 6
7 5
Our transformation:
Edge (1,2): add 1->2 w0, 2->1 w1
(3,2): add 3->2 w0, 2->3 w1
(3,4): add 3->4 w0, 4->3 w1
(7,4): add 7->4 w0, 4->7 w1
(6,2): add 6->2 w0, 2->6 w1
(5,6): add 5->6 w0, 6->5 w1
(7,5): add 7->5 w0, 5->7 w1
Now find shortest from 1 to 7 using 0-1 BFS. Let's compute manually: Starting at 1, neighbors: 2 (w0). So dist[2]=0, push front 2. From 2: neighbors: from original edges we added: 1->2 gave reverse 2->1 w1, so edge 2->1 w1; from (3,2) gave 2->3 w1; from (6,2) gave 2->6 w1. Also from (1,2) gave 2->1 w1? Actually we already listed. So from 2: edges: to1 w1, to3 w1, to6 w1. So all weight 1. Dist[2]=0. So relax: dist[1] = min(0+1,0)=0 (no change); dist[3]=1; dist[6]=1. Push back (since weight 1). So after processing node 2, we have dist[3]=1, dist[6]=1.
Now queue: initially had: [2] (pop front). After processing, we push back 3 and 6. So deque now: front maybe? Actually we push back, so deque becomes [3,6]? But if we push back for weight1, and we had nothing else, deque front = 3, back=6. Next pop front 3. From 3: edges: from (3,2): 3->2 w0; from (3,4): 3->4 w0; reverse edges: from (3,2): 2->3 already but that's incoming; Actually we added 2->3 w1; but from 3 perspective, we have outgoing edges: For original (3,2) we added edge 3->2 (w0) and 2->3 (w1). So from node 3, outgoing: to2 (w0) and to4 (w0) and also from any edge where 3 appears as target? For original (1,2) not involve 3. So also from (7,4) we added 4->7 w1, not relevant. So outgoing from 3: 3->2 w0, 3->4 w0. So relax dist[2] = min(1+0,0)=0 (no change). dist[4]= min(1+0, INF)=1? Actually dist[4] currently INF, so becomes 1. Since w0, push front 4. So after processing 3, we push front 4. Deque now: we had [3,6] after popping front 3, we had back 6. Then we push front 4, so deque becomes [4,6] (front 4, back 6). Next pop front 4. From 4: edges: from (3,4): 4->3 w1; from (7,4): 4->7 w1; also from (7,4): originally 7->4 gave 4->7 w1? Actually we added for (7,4): 7->4 w0 and 4->7 w1. So from node4 outgoing: to3 w1, to7 w1. So relax: dist[3]=min(1+1,1)=1 (no change). dist[7]=min(1+1, INF)=2. Since w1, push back 7. Deque now: [6,7] (after popping 4, we had [6], then push back 7 -> [6,7]). Next pop front 6. From 6: edges: from (6,2): 6->2 w0; from (5,6): 6->5 w1? Actually original (5,6): added 5->6 w0 and 6->5 w1. So from 6 outgoing: to2 w0, to5 w1. Relax: dist[2] currently 0, no change; dist[5]=min(1+1, INF)=2? Actually dist[6]=1, so 1+1=2 -> dist[5]=2. w1 -> push back 5. Deque now: [7,5] (since we had [6,7] popped 6, remaining [7], then push back 5 => [7,5]). Next pop front 7. From 7: edges: from (7,4): 7->4 w0; from (7,5): 7->5 w0; reverse edges: from (7,4): 4->7 w1 but that's incoming; from (7,5): 5->7 w1. So outgoing from 7: to4 w0, to5 w0. Relax: dist[4]=min(2+0,1)=1 (no change). dist[5]=min(2+0,2)=2 (no change). So nothing new. Deque now: [5]. Next pop front 5. From 5: edges: from (5,6): 5->6 w0; from (7,5): 5->7 w1. So outgoing: to6 w0, to7 w1. Relax: dist[6]=min(2+0,1)=1 no change; dist[7]=min(2+1,2)=2 no change. Done. So final dist[7]=2. Output 2. Matches example.
Thus solution is correct.
But wait: Are there any tricky aspects? For example, if there is already a path from 1 to N in original graph, answer is 0. That works: distances computed by 0-1 BFS will find a 0 cost path if exists.
Now we need to consider if there is any possibility that we need to reverse edges that are not on the final path to enable a shorter path? For instance, we might need to reverse an edge that is not traversed to create a new edge in the graph? But that would be equivalent to using that reversed edge as part of the path. Because if we reverse an edge, it can be used in the reversed direction. So it's just like using that edge in the path with cost 1. So any reversal that helps to create a path can be considered as an edge used in the path. So yes.
Therefore solution is straightforward.
Now, note that this problem is known as "Minimum edges to reverse to make path from source to destination", and it's often solved using 0-1 BFS or Dijkstra with weights 0/1.
Edge cases: N=1? If N=1, we already are at destination. Minimum reversals needed is 0. But there might be no path needed. In our BFS, dist[1]=0, output 0. Good.
If there is no way: maybe unreachable even after reversals: output -1.
Now, about multiple edges: works fine. Self loops: we can ignore. But careful: If there is a self loop on node 1 or N? Doesn't matter.
Complexities: O(N+M) time, O(N+M) memory.
Implementation details:
- Use vector of vector<pair<int, int>> for adjacency list.
- For each edge read (x,y):
if x != y:
adj[x].push_back({y, 0});
adj[y].push_back({x, 1});
else:
// self loop, ignore (or push both with 0? but not needed)
- Then 0-1 BFS.
We need to ensure we don't overflow the deque.
Alternative: Use Dijkstra with priority queue (since weights are 0/1, it's also O(E+V log V) but still fine for 1e5). But 0-1 BFS is simpler.
Now I'm thinking: Could there be a scenario where we need to reverse an edge that we also use in its original direction? That would be contradictory because after reversal it changes direction. But if we need both directions in the path, you cannot have that because a single directed edge can only have one direction after reversal. But our path is directed, so we only need edges oriented along the path. So it's fine.
Thus answer is simply the shortest distance.
But wait: The problem statement says: "minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to vertex N". This could also be interpreted as: we can reverse some edges, and after reversal, there must exist at least one directed path from 1 to N. But the reversal operation is global; we can reverse any edges. The cost is the number reversed. The path after reversal may use edges that were not reversed (original direction) and also edges that were reversed (now pointing in the opposite direction). So indeed the path in the transformed graph corresponds to a sequence of edges such that each edge either is original (if direction matches) or is reversed (if originally opposite). That's exactly our model.
But is there any possibility to achieve a path using edges that were not originally present as either direction? No.
Thus solution stands.
Now, let's test on some small cases:
Case 1: N=2, M=1, edge (1,2). Then we have adj[1] -> (2,0); adj[2] -> (1,1). BFS from 1: dist[2]=0, answer 0. Good.
Case 2: N=2, M=1, edge (2,1). Then we have adj[2] -> (1,0); adj[1] -> (2,1). BFS: from 1, neighbors: (2,1) so dist[2]=1, answer 1. So reverse that edge.
Case 3: N=3, edges: (1,3). Then direct path 0. But if not direct, maybe (1,2) and (2,3) reversed? Works.
Now, constraints: up to 100k edges, so adjacency list with 200k entries fine.
Potential pitfalls: Use of deque, large memory? fine.
Now we need to output -1 if unreachable. In BFS, if dist[N] remains INF, output -1.
Thus final code in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N, M;
cin >> N >> M;
vector<vector<pair<int, int>>> adj(N+1); // 1-indexed
for (int i = 0; i < M; i++) {
int x, y;
cin >> x >> y;
if (x == y) continue; // ignore self loop
adj[x].push_back({y, 0});
adj[y].push_back({x, 1});
}
const int INF = 1e9;
vector<int> dist(N+1, INF);
deque<int> dq;
dist[1] = 0;
dq.push_front(1);
while (!dq.empty()) {
int u = dq.front();
dq.pop_front();
for (auto &edge : adj[u]) {
int v = edge.first;
int w = edge.second;
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
if (w == 0) {
dq.push_front(v);
} else {
dq.push_back(v);
}
}
}
}
if (dist[N] == INF) cout << -1 << "\n";
else cout << dist[N] << "\n";
return 0;
}
Check: Should we treat when N=1? In BFS we push 1 and then process. dist[1]=0, answer 0. Works.
But note: For N=1, if M edges, we ignore. Works.
Now, test with example: yields 2.
Now, note that there could be multiple edges. Our code adds each as separate directed edges. That's fine because 0-1 BFS will consider each. If there are many parallel edges, it might increase adjacency list size but still within limits.
Now, think about correctness: The 0-1 BFS algorithm works because all edges have weight 0 or 1. It's essentially a BFS on a graph with 0-1 weights using deque to simulate a priority queue.
Now, question: Could there be a situation where reversing an edge not on the path can help reduce the number of reversals on the path? For instance, by reversing a certain edge, we might create a new vertex reachable without reversal? But that new edge would be used as part of a path. So the effect is that we can consider that reversed edge as part of a path. So the BFS captures it.
Now, what about reversing an edge that is used in both directions along the path? Not possible because path is directed.
Thus final answer is solved.
But wait, are there any hidden twists? The problem statement: "Sometimes mysteries happen." Not relevant.
Now let's re-read problem: "What is the minimum number of edges he needs to reverse in order to have at least one path from vertex 1 to vertex N." That's exactly it.
Thus solution is as above.
Now, possible edge case: The graph may be huge but we can still do 0-1 BFS.
Now, confirm with another example: Suppose N=3, M=3 edges: (1,2), (2,3), (3,1). Then from 1 to 3: path 1->2->3 uses original edges, so answer 0. BFS: from 1: (2,0) gives dist[2]=0; from 2: (3,0) gives dist[3]=0; answer 0. Good.
Suppose edges: (2,1), (2,3), (3,2). Then from 1 to 3: possible path 1->? we need edge from 1 to something. Original edges: (2,1) reversed gives 1->2 (cost1). Then from 2->3 original (2,3) cost0. So total cost1. Could also go 1->2 via reversal of (2,1) cost1, then maybe 2->3 via (2,3) cost0. So answer 1. BFS: from 1: neighbor (2,1) from (2,1) we added (1,2) with weight1? Actually (2,1) gives edge 2->1 w0 and 1->2 w1. So from 1, we have (2,1) weight1. So dist[2]=1. From 2: edges: (2,1) gave (2,1) w0? Wait careful: For original edge (2,1), we add adj[2].push_back({1,0}) and adj[1].push_back({2,1}). So from 2 we have (1,0) and (3,0) from (2,3) if exists? Actually we also have (2,3) edge: from original (2,3) we add adj[2].push_back({3,0}) and adj[3].push_back({2,1}). So from 2 we have (1,0) and (3,0). So when we process node 2 after it gets dist 1, then we relax (3,0): dist[3] = min(1+0, INF) =1. So answer 1. Good.
Now, what about using multiple reversals along a longer path? BFS finds minimal.
Thus solution is correct.
Now, there is another nuance: Some problems ask for minimum reversals to make the graph have a path from 1 to N, but allow reversing edges that are not on the path? But that is equivalent as we argued.
Let's confirm with a more complex scenario: Suppose there is a vertex that can only be reached by reversing an edge that is also needed in original direction for the path? That would be impossible because an edge cannot be both original and reversed. But perhaps we might need to reverse an edge that is not on the path to enable a path that uses some edges in original direction that were not originally present? Actually, if there is no edge between two vertices at all (neither direction), then no amount of reversal can create an edge between them. So path must only use pairs that have at least one directed edge originally. That's enforced by our modeling: we only have edges for each original edge in both directions, with appropriate costs.
Now, consider the possibility of using an edge in its original direction after it has been reversed for some other purpose? That would be contradictory. But if we reverse an edge, we change its direction globally. If we later need to use that same edge in its original direction on the path, that might not be possible. But does our model assume that each edge can be used only once? Actually, the path uses each edge at most once (since it's a simple path? Not necessarily; path may repeat vertices? Usually a path in a graph is simple? The problem says "at least one path". Typically in graph theory, a path is a sequence of vertices where each consecutive pair is connected by a directed edge, and vertices may not repeat? Usually path is simple (no repeated vertices) unless stated otherwise. But even if repeated vertices are allowed (walk), we can avoid cycles because they increase reversals. So optimal will be simple. However, if the graph has cycles, using an edge twice would require that the edge direction after reversals is fixed; if we traverse an edge twice in opposite directions, that would require the edge to be bidirectional, but after reversal it has a fixed direction. So if we need to traverse an edge both ways in the path, that's impossible with a fixed direction. So any valid directed path after reversals must respect the fixed direction of each edge after reversal. Our modeling using a path in the transformed graph ensures that we never try to use the same edge in both directions because we are constructing a directed walk in the transformed graph where each edge has a fixed direction. But could there be a situation where the optimal set of reversals results in a directed path that uses an edge twice? That would be suboptimal due to cycles. So we can ignore.
Thus, our solution is correct.
Now, let's implement final answer.
But note: The problem might be from CodeChef? There is known problem "Chef and Reversing" (REVERSE). Actually CodeChef problem "REVERSE" is exactly this: "Minimum edges to reverse to create a path from 1 to N". And solution is 0-1 BFS. So yes.
Thus final code as above.
We need to ensure to handle input efficiently, and use fast I/O.
Now, complexity: O(N+M). With N, M up to 1e5, it's fine.
Now, we also need to be careful about memory: vector of vectors of pairs. For each original edge we add two pairs. So at most 2e5 pairs. Each pair two ints, so memory ~ 221e5 = 0.8 MB plus overhead, but fine.
Now, think about potential pitfalls: In 0-1 BFS, we should only push when distance improves. That's done.
Now, test with a case where N unreachable: Suppose N=3, M=1, edge (1,2). Then from 1 we can reach 2, but not 3. After BFS dist[3] INF, output -1. Good.
Now, consider case where there is a self loop at 1 but no other edges: N=1? If N>1, then unreachable? Actually if N>1 and only self loops, then unreachable. Our BFS ignore self loops, so from 1, no outgoing edges; dist[1]=0, other nodes INF, output -1. Good.
Now, handle multiple test cases? The statement says "Each test file contains only one test case." So just one.
Thus final answer.
I'll write solution in Python as well? The user might want any language? The problem statement is generic. In this answer we can provide explanation and code in C++ (commonly used). But as per platform, we can provide Python too. But in final answer, we can give code in both? Usually we provide one language. I'll provide C++.
But as ChatGPT we need to output final answer in a code block? Actually the instruction: "You are an AI...Provide the final answer." But the user asked: "Sometimes mysteries happen...". They might want the solution. In typical interaction, we produce the code. However, sometimes they just want the answer? No, they provided example and want solution code? The problem is a programming problem, likely from a contest. They are asking for solution. So we should output the code. Possibly also explanation. But final answer should contain the code. I'll include explanation and then code.
But to be safe, I'll produce the code in C++.
Now, confirm with some additional tests:
Test 1: N=1, M=0. Output 0. Code: dist[1]=0, output 0.
Test 2: N=4, M=4 edges: (1,2),(3,2),(3,4),(4,1). Need path 1->4? Original: 1->2 (0), then from 2? only incoming? 2 has incoming from 1 and 3, but outgoing none? Actually edges: (1,2) gives 1->2; (3,2) gives 3->2; (3,4) gives 3->4; (4,1) gives 4->1. So from 1 we can go to 2; from 2 no outgoing (except reversed edges if we reverse (3,2) to 2->3? But that's a reversal). One possible path: reverse (4,1) to get 1->4? Actually (4,1) reversed yields 1->4 with cost1. So answer 1. BFS: from 1: neighbors: (2,0) from (1,2); (4,1) from (4,1) reverse? Yes, from edge (4,1) we added adj[1].push_back({4,1})? Actually (4,1) original gives adj[4] (4->1 w0) and adj[1] (1->4 w1). So from 1, (2,0) and (4,1). So dist[4]=1 (via direct reverse). So answer 1.
Test 3: N=5, edges: (1,2),(2,3),(3,4),(4,5) all forward, answer 0.
Test 4: N=5, edges: (5,4),(4,3),(3,2),(2,1) all backward. To get from 1 to5, need to reverse all edges along the path 1->2->3->4->5: each reversal cost1, total 4. Alternative: maybe other paths? none. So answer 4. BFS: from 1: neighbors: from (2,1) reversed? Edge (2,1) is original? Actually original (2,1) exists? Our edges are (5,4),(4,3),(3,2),(2,1). So (2,1) gives adj[2] (2->1 w0) and adj[1] (1->2 w1). So from 1: (2,1) gives dist[2]=1. Then from 2: edges: (2,1) original direction gives (2,1) w0, (3,2) reversed? Actually (3,2) is original? Edges: (3,2) exists? Actually original includes (3,2)? The list is (5,4),(4,3),(3,2),(2,1). So (3,2) gives adj[3] (3->2 w0) and adj[2] (2->3 w1). So from node 2 we have (1,0) from (2,1) and (3,1) from reverse of (3,2). So from 2 dist[3]= dist[2]+1 =2. Similarly, eventually dist[5]=4. So answer 4.
All good.
Now, consider if there are multiple edges with different costs? For each edge we add two directed edges. If there are multiple edges between same pair (u,v) in same direction, we add multiple 0-cost edges from u to v and multiple 1-cost from v to u. That's fine; shortest path will use the 0 cost if needed.
Now, note: The graph might be disconnected; BFS may not reach N.
Now, let's think about alternative approach: Could there be a faster solution? Not needed.
Now, discuss possible pitfalls with 0-1 BFS: We need to ensure we don't use too much memory for deque; but it's fine.
Now, code final.
But also: In some languages, we might use array of vectors. C++ is fine.
Now, finalize.
But wait, is there any scenario where the answer is not simply the shortest distance in this transformed graph? Let's think deeper: In our transformed graph, each step corresponds to either using an existing edge in its original direction (cost 0) or using the reverse of an existing edge (cost 1). However, in the final graph after reversing edges, an edge that we reversed becomes oriented in the opposite direction. Could that reversal affect the possibility of using other edges in their original direction? For instance, suppose we have two edges: (u,v) and (v,u). If we reverse (u,v) to (v,u), then we have two edges both (v,u) now. But then we can't use (u,v) in original direction because it's reversed. But maybe we needed (u,v) in original direction for the path? That would be a conflict. But in our path-based approach, we assume we only reverse edges that we need to use in the opposite direction along the path. But what if we need to reverse an edge that is also needed in its original direction somewhere else on the path? That can't happen because the path is directed and if we need both directions, the path would have to traverse that edge both ways, which would require that edge to be bidirectional. But after reversal, it's only one direction. However, it might be possible that the path uses the edge in its original direction in one segment, and some other path uses it reversed? But we only need at least one path. So we don't need both directions. So any edge we reverse we are okay losing its original direction because we only need the reversed direction for the path (or maybe not needed at all). However, there could be a scenario where the optimal set of reversals includes reversing an edge that is not on the chosen path, but that reversal inadvertently blocks another potential path that would have required that edge in original direction? But we are choosing the path after reversals. So if we reverse an edge not on our final path, that might break some other path, but we don't care about other paths; we just need at least one. So we can simply not reverse that edge. So minimal solution will never include unnecessary reversals.
Now, consider the scenario where we might want to reverse an edge that lies on a cycle that helps to reduce total reversals? For example, we might reverse an edge that creates a shortcut, but then also need to use some other edges that originally were not part of the path. But again, any edge reversed to create a shortcut would be used in the path (as part of the shortcut). So it's accounted.
Thus the model is correct.
Therefore, answer.
Now, let's write final response with explanation and code.
I'll produce final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N, M;
cin >> N >> M;
vector<vector<pair<int, int>>> adj(N + 1); // adjacency list: (neighbor, weight)
for (int i = 0; i < M; ++i) {
int x, y;
cin >> x >> y;
if (x == y) continue; // self‑loop is useless for a path
adj[x].emplace_back(y, 0); // original direction, cost 0
adj[y].emplace_back(x, 1); // reversed direction, cost 1
}
const int INF = 1e9;
vector<int> dist(N + 1, INF);
deque<int> dq;
dist[1] = 0;
dq.push_front(1);
// 0-1 BFS
while (!dq.empty()) {
int u = dq.front();
dq.pop_front();
for (auto [v, w] : adj[u]) {
if (dist[u] + w < dist[v]) {
dist[v] = dist[u] + w;
if (w == 0) {
dq.push_front(v);
} else {
dq.push_back(v);
}
}
}
}
if (dist[N] == INF) {
cout << -1 << "\n";
} else {
cout << dist[N] << "\n";
}
return 0;
}